【发布时间】: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