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

Unable to connect to Elasticsearch with PHP inside Docker

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

当我尝试通过 localhost:9200 访问 Elasticsearch 时,它起作用了。

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

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

这里是客户端代码:

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

现在它显示卷曲错误,即

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

您尝试连接到本地主机,但您需要连接到 "elastic" 主机。 尝试从 php 像这样连接到 elasticsearch:

$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.