gpt4 book ai didi

mongodb - 为什么我的mongo容器的docker-compose healthcheck总是失败?

转载 作者:可可西里 更新时间:2023-11-01 09:25:36 28 4
gpt4 key购买 nike

我正在使用 docker-compose 构建一个 Express/React/Mongo 应用程序。我目前可以在 express 应用程序中使用重试逻辑来解决所有问题。但是,我更愿意使用 Docker 的 healthcheck以防止容器最初旋转时出现错误字符串。但是,当我在 docker-compose.yml 中添加 healthcheck 时,它会在间隔/重试时间限制内挂起并退出:

ERROR: for collector  Container "70e7aae49c64" is unhealthy.

ERROR: for server Container "70e7aae49c64" is unhealthy.
ERROR: Encountered errors while bringing up the project.

我的健康检查似乎从未返回健康状态,我不完全确定原因。我的整个 docker-compose.yml:

version: "2.1"
services:
mongo:
image: mongo
volumes:
- ./data/mongodb/db:/data/db
ports:
- "${DB_PORT}:${DB_PORT}"
healthcheck:
test: echo 'db.runCommand("ping").ok' | mongo mongo:27017/test --quiet 1
interval: 10s
timeout: 10s
retries: 5
collector:
build: ./collector/
environment:
- DB_HOST=${DB_HOST}
- DB_PORT=${DB_PORT}
- DB_NAME=${DB_NAME}
volumes:
- ./collector/:/app
depends_on:
mongo:
condition: service_healthy
server:
build: .
environment:
- SERVER_PORT=$SERVER_PORT
volumes:
- ./server/:/app
ports:
- "${SERVER_PORT}:${SERVER_PORT}"
depends_on:
mongo:
condition: service_healthy

对于测试,我也尝试过:

["CMD", "nc", "-z", "localhost", "27017"] 

和:

["CMD", "bash", "/mongo-healthcheck"]

我也尝试完全放弃 healthcheck,遵循 this guy 的建议.一切正常,但在成功连接之前我在输出中遇到了可怕的错误:

collector_1  | MongoDB connection error: MongoNetworkError: failed to connect to server [mongo:27017] on first connect [MongoNetworkError: connect 
ECONNREFUSED 172.21.0.2:27017]
collector_1 | MongoDB connection with retry
collector_1 | MongoDB connection error: MongoNetworkError: failed to connect to server [mongo:27017] on first connect

最终目标是在运行 docker-compose up --build 时获得干净的启动输出。我还研究了 this question 中的一些解决方案。 ,但我在 wait-for-it 方面也不太走运。在启动其他容器并实现干净启动之前等待 Mongo 启动并运行的正确方法是什么?

最佳答案

首先,我建议将 docker-compose.yaml 文件版本更新到至少 3.4 (version: "3.5"),然后请添加 start_period您的 mongo healthcheck

选项

Note: start_period is only supported for v3.4 and higher of the compose file format.

start period provides initialization time for containers that need time to bootstrap. Probe failure during that period will not be counted towards the maximum number of retries. However, if a health check succeeds during the start period, the container is considered started and all consecutive failures will be counted towards the maximum number of retries.

所以它看起来像这样:

healthcheck:
test: echo 'db.runCommand("ping").ok' | mongo mongo:27017/test --quiet
interval: 10s
timeout: 10s
retries: 5
start_period: 40s

关于mongodb - 为什么我的mongo容器的docker-compose healthcheck总是失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54384042/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com