Docker Compose 健康检查与依赖服务启动顺序控制

在 Docker Compose 中,健康检查(healthcheck) 是控制服务启动顺序的核心机制,它确保依赖服务完全就绪后再启动后续服务。以下是实现方法:


1. 基础健康检查配置

在服务定义中添加 healthcheck 字段,通过命令检测服务状态:

services:
  database:
    image: postgres:14
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 10s

  • 参数说明
    • test:检测命令(返回 0 表示健康)
    • interval:检测间隔
    • timeout:命令超时时间
    • retries:失败重试次数
    • start_period:服务启动后的初始化缓冲时间

2. 依赖服务启动顺序控制

通过 depends_on + condition 实现依赖关系:

services:
  webapp:
    image: nginx:alpine
    depends_on:
      database:
        condition: service_healthy  # 关键配置
    ports:
      - "80:80"

  • 效果webapp 服务会等待 database 的健康检查通过后才启动
  • 注意:仅 Compose 文件版本 ≥ 2.1 支持此语法

3. 多服务依赖示例
services:
  redis:
    image: redis:6
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      ...
  
  database:
    image: postgres:14
    healthcheck: ...
  
  backend:
    image: node:18
    depends_on:
      redis:
        condition: service_healthy
      database:
        condition: service_healthy
  
  frontend:
    image: nginx
    depends_on:
      backend:
        condition: service_healthy


4. 健康检查脚本进阶用法

对于复杂场景(如等待数据库初始化完成),使用自定义脚本:

#!/bin/bash
# wait-for-db.sh
until psql -h "$1" -U "postgres" -c '\q'; do
  >&2 echo "Database unavailable - sleeping"
  sleep 2
done

在 Compose 中调用:

services:
  backend:
    ...
    command: ["./wait-for-db.sh", "database"]
    depends_on:
      database:
        condition: service_started  # 仅要求容器启动


5. 常见问题解决
  • Q:服务卡在 starting 状态?
    A:检查健康检测命令返回值(必须返回 0),或延长 start_period

  • Q:旧版本 Compose 不支持 condition
    A:使用第三方工具如 wait-for-it

    command: ["./wait-for-it.sh", "database:5432", "--", "start-app.sh"]
    


验证命令

查看服务健康状态:

docker-compose ps

输出示例:

  Name                Command              State           Ports         
------------------------------------------------------------------
db          docker-entrypoint.sh postgres   Up (healthy)   5432/tcp
webapp      nginx -g daemon off;            Up             0.0.0.0:80->80/tcp

通过健康检查机制,可精确控制服务启动顺序,避免因依赖未就绪导致的启动失败问题。

更多推荐