How to Use Healthcheck in Docker Compose for Container Monitoring
In
docker-compose.yml, use the healthcheck key under a service to define a command that tests container health. Specify test, interval, timeout, retries, and start_period to control how Docker checks the container's status.Syntax
The healthcheck section in docker-compose.yml defines how Docker tests if a container is healthy. It includes:
- test: The command Docker runs to check health.
- interval: How often to run the test (default 30s).
- timeout: How long to wait for the test to finish (default 30s).
- retries: Number of failures before marking unhealthy (default 3).
- start_period: Time to wait after container start before testing.
yaml
services:
myservice:
image: myimage
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 30s
timeout: 10s
retries: 3
start_period: 5sExample
This example shows a web service with a healthcheck that tries to fetch the homepage every 10 seconds. If the command fails 3 times in a row, Docker marks the container as unhealthy.
yaml
version: '3.8' services: web: image: nginx:1.23 ports: - "8080:80" healthcheck: test: ["CMD", "curl", "-f", "http://localhost"] interval: 10s timeout: 5s retries: 3 start_period: 5s
Output
docker-compose up -d
# After startup, run:
docker ps
# The STATUS column will show "healthy" if the healthcheck passes.
Common Pitfalls
Common mistakes include:
- Using
test: curl http://localhostas a string instead of an array, which can cause parsing errors. - Not setting
start_period, causing healthchecks to fail during container startup. - Setting too short
timeoutorinterval, leading to false unhealthy states.
yaml
services:
badservice:
image: busybox
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 5s
timeout: 1s
retries: 1
# Correct way:
services:
goodservice:
image: busybox
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10sQuick Reference
| Field | Description | Default |
|---|---|---|
| test | Command to check container health | Required |
| interval | Time between checks | 30s |
| timeout | Max time to wait for test | 30s |
| retries | Failures before unhealthy | 3 |
| start_period | Startup grace period | 0s |
Key Takeaways
Use the healthcheck section in docker-compose.yml to monitor container health.
Define the test command as an array for reliable parsing.
Adjust interval, timeout, retries, and start_period to fit your app's startup and response times.
Healthchecks help Docker know when a container is ready or needs restarting.
Avoid too frequent or too short healthchecks to prevent false failures.