我正在尝试使用 Python 客户端为容器化 Elasticsearch 数据库建立索引 https://github.com/elastic/elasticsearch-py从脚本调用(也在容器中运行)。
通过查看现有的代码片段,似乎docker-compose
对于我的目的来说是一个有用的工具。我的目录结构是
docker-compose.yml
indexer/
- Dockerfile
- indexer.py
- requirements.txt
elasticsearch/
- Dockerfile
我的docker-compose.yml
读取
version: '3'
services:
elasticsearch:
build: elasticsearch/
ports:
- 9200:9200
networks:
- deploy_network
container_name: elasticsearch
indexer:
build: indexer/
depends_on:
- elasticsearch
networks:
- deploy_network
container_name: indexer
networks:
deploy_network:
driver: bridge
indexer.py
读取
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
es = Elasticsearch(hosts=[{"host":'elasticsearch'}]) # what should I put here?
actions = [
{
'_index' : 'test',
'_type' : 'content',
'_id' : str(item['id']),
'_source' : item,
}
for item in [{'id': 1, 'foo': 'bar'}, {'id': 2, 'foo': 'spam'}]
]
# create index
print("Indexing Elasticsearch db... (please hold on)")
bulk(es, actions)
print("...done indexing :-)")
elasticsearch 服务的 Dockerfile 是
FROM docker.elastic.co/elasticsearch/elasticsearch-oss:6.1.3
EXPOSE 9200
EXPOSE 9300
索引器的值是
FROM python:3.6-slim
WORKDIR /app
ADD . /app
RUN pip install -r requirements.txt
ENTRYPOINT [ "python" ]
CMD [ "indexer.py" ]
其中 requirements.txt
仅包含要使用 pip 下载的 elasticsearch
。
使用docker-compose run indexer
运行会给我https://pastebin.com/6U8maxGX处的错误消息(ConnectionRefusedError:[Errno 111] 连接被拒绝
)。
据我所知,使用curl -XGET 'http://localhost:9200/'
或运行docker ps -a
,elasticsearch已经启动。
如何修改我的 docker-compose.yml
或 indexer.py
来解决问题?
附注为了完整起见,可以在此处找到代码的(工作)版本(由下面的答案通知):https://github.com/davidefiocco/dockerized-elasticsearch-indexer .
最佳答案
问题是同步错误:当 indexer
尝试连接到 elasticsearch
时,它尚未完全启动。您必须添加一些重试逻辑,以确保在尝试针对 Elasticsearch 运行查询之前它已启动并运行。像在循环中运行 es.ping()
直到它以指数退避成功应该可以解决问题。
更新:Docker HEALTHCHECK
指令可用于实现类似的结果(即,在尝试对其运行查询之前,请确保 elasticsearch
已启动并正在运行)。
关于python - 如何使用在 docker 容器中运行的 python 脚本创建(dockerized)Elasticsearch 索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48711455/