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

Rah*_*eel 8 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"
Run Code Online (Sandbox Code Playgroud)

当我尝试访问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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

用于实例化Elasticsearch对象的代码:

<?php

require 'vendor/autoload.php';

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

$es = Client::getClient();
Run Code Online (Sandbox Code Playgroud)

如果我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'));
Run Code Online (Sandbox Code Playgroud)

更新

此处输入链接描述

这一页.我试过了

$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());
}
Run Code Online (Sandbox Code Playgroud)

现在它显示我卷曲错误即

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

Buk*_*gey 7

您尝试连接到localhost,但您需要连接到"弹性"主机.尝试从php连接到elasticsearch,如下所示:

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

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