Skip to content

健康检查失败:容器被标记为不健康

快速摘要

你的容器健康检查失败 —— 健康检查命令返回非零退出码。

为什么发生

  • 检查运行时健康检查端点或命令尚未就绪

  • 健康检查间隔或启动期对于应用初始化来说太短

  • 健康检查命令本身有错误或测试了错误的端点

最小示例

✗ 错误代码
# docker-compose.yml
services:
  app:
    image: myapp:latest
    healthcheck:
      test: ['CMD', 'curl', '-f', 'http://localhost:3000/health']
      interval: 5s
      start_period: 2s # too short — app needs 10s to start
✓ 修复代码
# docker-compose.yml
services:
  app:
    image: myapp:latest
    healthcheck:
      test: ['CMD', 'curl', '-f', 'http://localhost:3000/health']
      interval: 10s
      start_period: 30s # enough time for app to initialize
      retries: 3

将启动期增大到 30s 给应用足够的时间在健康检查开始前初始化。

如何诊断

  • 用 docker inspect 检查容器健康状态并查看健康日志

  • 在容器内手动运行健康检查命令以查看错误

  • 查看健康检查配置的间隔、超时和启动期是否正确

如何修复

  • 增大启动期以给应用更多初始化时间

  • 修复健康检查命令以测试正确的端点或条件

  • 添加重试逻辑或增大重试次数以处理瞬时健康检查失败

如何预防

  • 根据应用启动时间设置适当的健康检查间隔和启动期

  • 在添加到容器配置前手动测试健康检查命令

相关资源

相关术语

相关课程

← 返回语言