无法使用Docker中的PHP连接到Elasticsearch

时间:2016-07-30 09:55:01

标签: php elasticsearch docker docker-compose

这是我的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"

当我尝试访问Elasticsearch时,转到localhost:9200就可以了。

但是当我尝试使用PHP创建索引时,我收到以下错误:

  

致命错误:未捕获   Elasticsearch \ Common \ Exceptions \ NoNodesAvailableException:没有活着   

中的群集中找到的节点

以下是客户端代码:

<?php

namespace App\Elasticsearch;

use Elasticsearch\ClientBuilder;

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

实例化Elasticsearch对象的代码:

<?php

require 'vendor/autoload.php';

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

$es = Client::getClient();

如果我var_dump($es),它会转储Elasticsearch客户端对象。

但是当我尝试创建索引时,它会抛出一个错误。

<?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'));

更新

来自enter link description here

此页面。我试着

$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());
}

现在它显示了卷曲错误,即

  

[&#34; curl&#34;] array(2){[&#34; error&#34;]&#34;无法连接到localhost端口   9200:连接被拒绝&#34; [&#34; errno&#34;] 7

1 个答案:

答案 0 :(得分:6)

您尝试连接到localhost,但您需要连接到“弹性”主机。 尝试从php连接到elasticsearch:

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

链接服务的容器可以在与别名相同的主机名上访问,如果没有指定别名,则可以访问服务名称。