Health Check Setup
Intermediate10 min
Configure container health checks so Docker can automatically detect unhealthy containers and orchestrators can restart them.
Prerequisites
- -Docker installed
Steps
1
Add HEALTHCHECK to a Dockerfile
Define a health check command that Docker runs periodically to determine if the container is healthy.
$ echo 'HEALTHCHECK --interval=30s --timeout=10s --retries=3 CMD curl -f http://localhost:3000/health || exit 1'
Adjust interval and timeout based on your application's startup time and response characteristics.
2
Add health check in Docker Compose
Configure health checks in your compose file for each service.
$ cat <<'EOF'
services:
api:
image: myapp:latest
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
EOF
3
Check container health status
View the health status and recent health check results.
$ docker inspect <container-name> --format '{{.State.Health.Status}}: {{range .State.Health.Log}}{{.Output}}{{end}}'
4
View health check history
See the last few health check results including timestamps and output.
$ docker inspect <container-name> --format '{{json .State.Health}}' | jq '.Log[-3:]'
Full Script
FAQ
Discussion
Loading comments...