如何为Elasticsearch的docker-compose.yml配置预导入索引数据的存储卷
Elasticsearch 自动初始化索引数据配置方案
首先明确:Elasticsearch 官方镜像没有内置类似PostgreSQL的/docker-entrypoint-initdb.d自动执行初始化脚本的机制,需要额外添加初始化辅助服务实现需求,具体配置步骤如下:
1. 准备初始化脚本
在本地新建./docker/es-init目录,在目录下创建init-es.sh脚本(扩展名使用.sh即可,本质是调用curl执行ES API的shell脚本),脚本内容如下:
#!/bin/sh # 等待ES服务完全启动 until curl -s http://elasticsearch:9200/_cluster/health | grep -E '"status":"(green|yellow)"' > /dev/null; do echo "等待Elasticsearch启动中..." sleep 2 done # 创建test索引 curl -X PUT "http://elasticsearch:9200/test" -H "Content-Type: application/json" # 批量导入数据 curl -X POST "http://elasticsearch:9200/_bulk" -H "Content-Type: application/x-ndjson" --data-binary @- <<EOF { "index" : { "_index" : "test"} } { "name" : "A" } { "index" : { "_index" : "test"} } { "name" : "B" } { "index" : { "_index" : "test"} } { "name" : "C" } { "index" : { "_index" : "test"} } { "name" : "D" } EOF echo "ES初始化数据完成"
给本地脚本加执行权限:chmod +x ./docker/es-init/init-es.sh
2. 修改docker-compose.yml配置
需要给ES服务新增健康检查,同时新增独立的初始化服务,修改后完整配置如下:
version: '3.7' services: elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:7.4.0 container_name: elasticsearch environment: - xpack.security.enabled=false - discovery.type=single-node ulimits: memlock: soft: -1 hard: -1 nofile: soft: 65536 hard: 65536 cap_add: - IPC_LOCK volumes: - elasticsearch-data:/usr/share/elasticsearch/data ports: - 9200:9200 - 9300:9300 # 新增健康检查,判断ES是否启动完成 healthcheck: test: ["CMD-SHELL", "curl -s http://localhost:9200/_cluster/health | grep -E '\"status\":\"(green|yellow)\"'"] interval: 2s timeout: 10s retries: 30 # 新增ES初始化服务 es-init: image: alpine/curl:3.18 container_name: es-init volumes: # 挂载本地初始化脚本目录到容器内 - ./docker/es-init:/init depends_on: elasticsearch: condition: service_healthy command: ["/bin/sh", "/init/init-es.sh"] kibana: container_name: kibana image: docker.elastic.co/kibana/kibana:7.4.0 environment: - ELASTICSEARCH_HOSTS=http://elasticsearch:9200 ports: - 5601:5601 depends_on: elasticsearch: condition: service_healthy volumes: elasticsearch-data: driver: local
3. 执行说明
首次启动时es-init服务会自动等待ES就绪后执行索引创建和数据导入,导入完成后该服务会自动退出。如果数据卷elasticsearch-data已经存在(即ES已经初始化过),可以手动注释掉es-init服务避免重复执行导入逻辑。
内容的提问来源于stack exchange,提问作者Alex Man
相关产品推荐
相关产品推荐

