Raheel Khan Raheel Khan - 4 months ago 95
PHP Question

Unable to connect to Elasticsearch with PHP inside Docker

Here is my

docker-compose.yml


nginx:
build: ./nginx/
ports:
- 80:80
links:
- php
volumes_from:
- app

php:
image: php:7.0-fpm
expose:
- 9000
volumes_from:
- app
links:
- elastic

app:
image: php:7.0-fpm
volumes:
- .:/var/www/html
command: "true"

elastic:
image: elasticsearch:2.3
volumes:
- ./elasticsearch/data:/usr/share/elasticsearch/data
- ./elasticsearch/logs:/usr/share/elasticsearch/logs
expose:
- "9200"
ports:
- "9200:9200"


While i try to access elastic search by going to
localhost:9200
it works.

But when i am trying to create index from PHP it gives


Fatal error: Uncaught
Elasticsearch\Common\Exceptions\NoNodesAvailableException: No alive
nodes found in your cluster in


Here is how i create client

<?php

namespace App\Elasticsearch;

use Elasticsearch\ClientBuilder;

class Client
{
public static function getClient()
{
return ClientBuilder::create()
->build();
}
}


Here is how i get elastic search object

<?php

require 'vendor/autoload.php';

use App\Elasticsearch\Client;
use App\Elasticsearch\Indices\UserIndex;

$es = Client::getClient();


If I
var_dump($es)
it dumps the Elasticsearch Client object.

But when i attempt to create Index it throws error.

<?php

namespace App\Elasticsearch\Indices;

use App\Elasticsearch\Indices\AbstractIndex;
use Elasticsearch\Client;

class UserIndex extends AbstractIndex
{
public function __construct(Client $client)
{
$this->client = $client;
}
}

// Create User Index
$userIndex = new UserIndex($es);
var_dump($userIndex->createIndex('users'));


Update

From enter link description here

this page. I tried to

$es = Client::getClient();

try {
// Create User Index
$userIndex = new UserIndex($es);
var_dump($userIndex->createIndex('users'));
} catch (Exception $e) {
var_dump($es->transport->getLastConnection()->getLastRequestInfo());
}


and now it shows me Curl error i.e


["curl"] array(2) { ["error"] "Failed to connect to localhost port
9200: Connection refused" ["errno"] 7

Answer

You tried to connect to localhost, but you need to connect to "elastic" host. try to connect to elasticsearch from php like this:

$hosts = [
    'elastic', // elastic host was added to you hosts file automatically
];
$client = ClientBuilder::create()
   ->setHosts($hosts)
   ->build();

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.

Comments