Python:docker-compose 上的 Elasticsearch 连接被拒绝

问题描述 投票:0回答:1

我正在尝试使用

elasticsearch==8.17.0
连接到 Python 中的 Elasticseach 实例,但我遇到了 Errno 111 Connection Refused 问题。

在 docker/Exec 中运行

bin/elasticsearch-users useradd base-user -p base-password
实际上应该添加相关的用户默认角色。

services: 

jupyter:
    container_name: jupyter
    build: 
      context: .
      dockerfile: ./jupyter/Dockerfile
    environment:
      - [...]
    volumes:
      - ./work:/home/jovyan/work
    ports:
      - 8888:8888

 elasticsearch:
    container_name: elasticsearch
    image: docker.elastic.co/elasticsearch/elasticsearch:8.17.0
    ports:
      - 9200:9200
    mem_limit: 1G
    environment:
      - xpack.security.enabled=false
      - discovery.type=single-node

      # - xpack.security.transport.ssl.enabled=false
      # - xpack.security.http.ssl.enabled=false

   [...]

Python代码:

from elasticsearch import Elasticsearch

elasticsearch_client = Elasticsearch(
    [
        {
            'host':"localhost",
            'port':9200,
            'scheme': "http"
        }
    ], 
    basic_auth=(str("base-username"), str("base-password"))
    )
print(elasticsearch_client.info())

错误:

ConnectionError: Connection error caused by:
    ConnectionError(Connection error caused by:
        NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7fee981ead80>:
             Failed to establish a new connection: [Errno 111] Connection refused))

最后我尝试了:

python elasticsearch docker-compose
1个回答
0
投票

尝试将您的 Python 代码更改为

from elasticsearch import Elasticsearch

elasticsearch_client = Elasticsearch(
    [
        {
            'host':"elasticsearch",
            'port':9200,
            'scheme': "http"
        }
    ], 
    basic_auth=(str("base-username"), str("base-password"))
    )

print(elasticsearch_client.info())

同一 Docker 网络上的容器可以使用其主机名进行通信。

当您设置

'host':"localhost"

 时,您将尝试连接到 
jupyter
 容器而不是 
elasticsearch

© www.soinside.com 2019 - 2024. All rights reserved.