【问题标题】:Using elasticsearch inside Docker: Failed to establish a new connection在 Docker 中使用 elasticsearch:无法建立新连接
【发布时间】:2020-05-09 01:07:55
【问题描述】:

我目前正在尝试容器化一个应用程序,其中包括使用 Elasticsearch 写入数据库,但遇到连接问题。 docker-compose.yml 文件目前看起来像这样:

version: "3"
services:
  es:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.5.1
    container_name: es
    environment:
      - node.name=es
      - cluster.name=es-docker-cluster
      - cluster.initial_master_nodes=es
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    ports:
      - 9200:9200
    volumes:
      - esdata:/usr/share/elasticsearch/data
    networks:
      - dash-network
  dash:
    build: .
    depends_on:
      - es
    ports:
      - 5000:5000
    volumes:
       - .:/usr/src/dash
    networks:
      - dash-network

volumes:
  esdata:
    driver: local

networks:
  dash-network:
    driver: bridge

我的 Python 代码包括以下内容:

import elasticsearch
es = elasticsearch.Elasticsearch([{'host': 'es', 'port': 9200}])
es.index(index="spam", body={'eggs': 11})

但是,当我运行 docker-compose up 时,该代码段的最后一行会出现以下错误:

esmqtt_1   | elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f2f60b53dd0>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f2f60b53dd0>: Failed to establish a new connection: [Errno 111] Connection refused)

作为一个实验,我在脚本运行这段代码之前暂停了很长时间,将其放入容器中,然后依次运行这三个命令中的每一个。成功了:

elliot@elliot-VirtualBox:~/path/to/dash$ sudo docker exec -it dash_dash_1 sh
# python
Python 3.7.6 (default, Jan  3 2020, 23:24:26) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import elasticsearch
>>> es = elasticsearch.Elasticsearch([{'host': 'es', 'port': 9200}])
>>> es.index(index="spam", body={'eggs': 11})
{'_index': 'spam', '_type': '_doc', '_id': '3Ey5zm8B7hzXos4SVZsF', '_version': 1, 'result': 'created', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 0, '_primary_term': 1}

我不知道为什么我的代码在由 Dockerfile 运行时会失败,但是当我进入 shell 时,它可以工作。为什么前一种连接失败,后一种连接成功?欢迎所有提示或建议!

【问题讨论】:

    标签: docker elasticsearch docker-compose containers elasticsearch-py


    【解决方案1】:

    它试图同时运行不同的容器,导致dash 容器在 Elasticsearch 完成设置之前尝试连接。我现在使用以下循环来检查它是否准备就绪,然后再继续。

    while True:
        try:
            es.search(index="")
            break
        except (
            elasticsearch.exceptions.ConnectionError,
            elasticsearch.exceptions.TransportError
        ):
            time.sleep(1)
    

    【讨论】:

    • 这里介绍的工作不是 docker compose 中的depends_on 应该做的吗?确保在从依赖容器中使用依赖容器之前启动依赖容器?
    • @user007 我的大部分 Docker 经验都已经生锈了,所以我不能告诉你。也许我使用了一些不推荐使用的格式或其他东西。
    猜你喜欢
    • 2017-05-14
    • 2020-02-01
    • 2016-12-04
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 2019-05-30
    • 2020-09-14
    • 1970-01-01
    相关资源
    最近更新 更多