depends_on: [db] 默认只保证容器启动,不代表数据库已经能接收连接。需要等健康检查通过,可以把依赖写成这样:
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: devpass
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 2s
timeout: 3s
retries: 10
app:
image: busybox:1.36
depends_on:
db:
condition: service_healthy
command: ["sh", "-c", "echo db ready"]
保存后运行 docker compose up,app 会等 db 通过 healthcheck 再启动。环境是 Docker Engine 24+、Docker Compose v2;真实应用还要保留自己的重试或连接失败处理,健康检查只能减少启动时序问题。