gpt4 book ai didi

php - 无法在 Docker 中使用 PHP 连接到 Elasticsearch

转载 作者:IT老高 更新时间:2023-10-28 21:25:44 26 4
gpt4 key购买 nike

这是我的 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 错误,即

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

最佳答案

您尝试连接到 localhost,但您需要连接到“弹性”主机。尝试像这样从 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.

关于php - 无法在 Docker 中使用 PHP 连接到 Elasticsearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38672594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com