How to add health checks in Docker Compose?
· Category: Docker
Short answer
Health checks in Docker Compose verify that a service is healthy before other services depend on it. Define them with the healthcheck key in the Compose file or the HEALTHCHECK instruction in a Dockerfile.
Steps
- Add a
healthchecksection to the service indocker-compose.yml. - Specify the test command, interval, timeout, retries, and start period.
- Use
depends_onwithcondition: service_healthyfor dependency ordering.
Example
services:
db:
image: postgres:15
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
app:
image: myapp
depends_on:
db:
condition: service_healthy
Tips
- Keep health check commands lightweight to avoid resource overhead.
- Use
start_periodto give slow-starting services time before counting failures. - Check health status with
docker compose ps.
Common issues
condition: service_healthyrequires Compose file version 3.4 or higher with Docker Compose v2.- Misconfigured health checks can cause endless restart loops.
- Ensure the health check command exists inside the container image.