健康检查配置

Docker 容器的健康检查配置,使用 HEALTHCHECK 指令


📋 目录


HEALTHCHECK 语法

基本语法

HEALTHCHECK [OPTIONS] CMD command

选项说明

  • --interval=DURATION:检查间隔(默认 30s)
  • --timeout=DURATION:超时时间(默认 30s)
  • --start-period=DURATION:启动宽限期(默认 0s)
  • --retries=N:失败重试次数(默认 3)

基本示例

# 简单的健康检查
HEALTHCHECK CMD curl -f http://localhost:80/ || exit 1
 
# 带选项的健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:80/ || exit 1

健康检查脚本

HTTP 健康检查

# 检查 HTTP 端点
HEALTHCHECK --interval=30s --timeout=3s \
  CMD curl -f http://localhost:8080/health || exit 1
 
# 使用 wget
HEALTHCHECK CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1

TCP 健康检查

# 检查 TCP 端口
HEALTHCHECK --interval=30s --timeout=3s \
  CMD nc -z localhost 3306 || exit 1

自定义脚本

# 使用自定义脚本
HEALTHCHECK --interval=30s --timeout=3s \
  CMD /app/healthcheck.sh || exit 1

数据库健康检查

# MySQL 健康检查
HEALTHCHECK --interval=30s --timeout=3s \
  CMD mysqladmin ping -h localhost || exit 1
 
# PostgreSQL 健康检查
HEALTHCHECK --interval=30s --timeout=3s \
  CMD pg_isready -U postgres || exit 1

健康状态监控

查看健康状态

# 查看容器健康状态
docker ps
 
# 查看详细健康检查信息
docker inspect --format='{{json .State.Health}}' my-container | jq
 
# 查看健康检查日志
docker inspect --format='{{range .State.Health.Log}}{{.Output}}{{end}}' my-container

健康状态值

  • starting:容器启动中
  • healthy:健康检查通过
  • unhealthy:健康检查失败

自动重启策略

结合 —restart

# 健康检查失败时重启
docker run -d \
  --name my-app \
  --restart=on-failure \
  myapp:latest

Docker Compose 中的健康检查

version: '3.8'
services:
  web:
    image: nginx:latest
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:80/"]
      interval: 30s
      timeout: 3s
      retries: 3
      start_period: 40s

最佳实践

1. 合理设置检查间隔

# 根据应用特性设置
HEALTHCHECK --interval=30s --timeout=3s \
  CMD curl -f http://localhost:8080/health || exit 1

2. 设置启动宽限期

# 给应用启动时间
HEALTHCHECK --interval=30s --timeout=3s --start-period=60s \
  CMD curl -f http://localhost:8080/health || exit 1

3. 使用轻量级检查

# 使用轻量级命令,避免影响性能
HEALTHCHECK CMD curl -f http://localhost:8080/health || exit 1

4. 检查关键服务

# 检查应用的关键功能
HEALTHCHECK CMD curl -f http://localhost:8080/api/health || exit 1

实用示例

Web 应用

FROM nginx:alpine
COPY . /usr/share/nginx/html
HEALTHCHECK --interval=30s --timeout=3s \
  CMD wget --no-verbose --tries=1 --spider http://localhost:80/ || exit 1

API 服务

FROM node:16
WORKDIR /app
COPY . .
RUN npm install
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s \
  CMD node healthcheck.js || exit 1
CMD ["node", "index.js"]

数据库

FROM postgres:13
HEALTHCHECK --interval=30s --timeout=3s \
  CMD pg_isready -U postgres || exit 1

📚 参考资源


相关笔记