docker-compose-error-service-unhealthy-dependency-fix
启动 docker compose 时应用服务因依赖的数据库或中间件未就绪报错 dependency failed to start: service database is unhealthy。本文详解 healthcheck 参数调优与 condition: service_healthy 最佳实践。
问题现象
在执行 docker compose up 部署微服务集群时,主服务在尝试启动时被系统阻断并报错:
ERROR: for app Container "a1b2c3d4e5f6" is unhealthy
dependency failed to start: service "database" is unhealthy
主应用容器根本没有启动,依赖的数据库容器虽然在运行,但状态标记为 (unhealthy)。
触发根因
在 docker-compose.yml 中配置了高级依赖条件 depends_on: { service: { condition: service_healthy } }:
- 健康检查命令(test)未在容器内安装对应工具:例如在轻量级 Alpine 镜像中配置了
test: ["CMD", "curl", "-f", "http://localhost:80"],但镜像根本没有预装curl工具,命令执行恒返回 127。 - 冷启动初始化耗时超过 start_period 宽限期:数据库(如 MySQL / PostgreSQL)在初次启动时需要初始化数据目录并执行系统迁移,耗时长达 30~60 秒。而健康检查设置了极短的间隔(如
interval: 5s, retries: 3),在数据库初始化完成前就提前判定为失败。 - 健康检查端口或认证凭据错误:使用了错误的用户名密码探测数据库连通性。
诊断排查步骤
1. 查看不健康容器的健康检查失败日志
Docker 会记录最近 5 次健康检查执行的详细终端输出:
docker inspect --format='{{json .State.Health}}' $(docker compose ps -q database) | jq
输出示例:
{
"Status": "unhealthy",
"FailingStreak": 5,
"Log": [
{
"ExitCode": 127,
"Output": "/bin/sh: curl: not found
"
}
]
}
日志清晰指出是因为容器内缺失 curl 导致检测一直失败。
解决方案
方案一:为健康检查补充 start_period 启动宽限期(关键核心)
在 docker-compose.yml 中添加 start_period,在冷启动阶段允许失败而不计入重试次数:
services:
database:
image: postgres:15-alpine
environment:
POSTGRES_DB: mydb
POSTGRES_USER: myuser
POSTGRES_PASSWORD: mypassword
healthcheck:
# 使用 Postgres 原生自带的 pg_isready 工具,无需依赖 curl
test: ["CMD-SHELL", "pg_isready -U myuser -d mydb"]
interval: 10s
timeout: 5s
retries: 5
start_period: 40s # 给初次初始化预留 40 秒缓冲宽限期
app:
image: my-app:latest
depends_on:
database:
condition: service_healthy
针对 MySQL 容器的无工具原生健康检查:
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
针对 Redis 容器的健康检查:
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 3
方案二:针对无原生工具的 Web 容器使用 wget 或 sh 内建套接字
如果是极简 Web 容器(缺少 curl),改用通常内置的 wget:
healthcheck:
test: ["CMD-SHELL", "wget -q --spider http://127.0.0.1:8080/health || exit 1"]
或者使用纯 Bash 内建 TCP 套接字检测端口:
healthcheck:
test: ["CMD-SHELL", "cat < /dev/null > /dev/tcp/127.0.0.1/8080 || exit 1"]
验证方法
重新启动 Compose 栈:
docker compose down
docker compose up -d
通过 docker compose ps 观察容器状态演进:
数据库在经历短暂 (health: starting) 后迅速转为 (healthy),主应用紧随其后顺利拉起并在 Up 状态稳定运行,依赖编排完全就绪。


