Overview and What You Will Learn
A Docker Compose health check is a probe command that tells Compose whether a service is actually ready, not merely started. Combined with depends_on and condition: service_healthy, it stops an API from booting before its database accepts connections, which is the cause of most "connection refused" crash loops in Compose stacks.
In this lab you will:
- See why plain
depends_onguarantees start order but not readiness. - Write health checks for PostgreSQL, Redis, RabbitMQ, and an HTTP service.
- Gate startup with
service_healthyand usedocker compose up --wait. - Read health states and debug a check that never turns healthy.
- Know when a script such as
wait-for-it.shis still the right tool.
Why This Matters in Production
A payments service that starts before its Redis-backed rate limiter is ready will either crash on boot or run unprotected for its first seconds of traffic. Neither is acceptable, and a sleep 10 in an entrypoint script only hides the problem until a slow day makes it fail again. A real health check turns readiness into a contract that Compose can enforce and that CI can reuse.
The same probe definition also carries over to production. Kubernetes readiness probes and load balancer checks solve the identical problem, so a well-designed /health endpoint pays off in every environment.
Core Principles
depends_on without a condition only waits for the dependency container to be created and started. The database process inside may need several more seconds to finish initialising.
Remember these facts:
- Three health states exist:
starting,healthy, andunhealthy. Failures duringstart_perioddo not count towardretries. - Exit code decides the result: the probe exits
0for healthy and1for unhealthy. - Three
depends_onconditions exist:service_started(default),service_healthy, andservice_completed_successfully(for one-shot jobs such as migrations). - Dependencies are checked at startup only. If a database becomes unhealthy later, Compose does not stop or restart the API.
- Docker only records the status. A restart policy reacts to process exits, not to health status.
Detailed Step-by-Step Practical Lab
How to Write a Health Check for Common Services
services: postgres: image: postgres:16-alpine environment: POSTGRES_DB: ratelimits POSTGRES_USER: api_user POSTGRES_PASSWORD: ${DB_PASSWORD:-devpassword} healthcheck: test: ["CMD-SHELL", "pg_isready -U api_user -d ratelimits"] interval: 5s # how often to run the probe timeout: 3s # a single probe must finish within this time retries: 5 # consecutive failures before unhealthy start_period: 10s # failures in this window are ignored redis: image: redis:7-alpine healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 5s timeout: 3s retries: 5 rabbitmq: image: rabbitmq:3-management-alpine healthcheck: test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] interval: 10s timeout: 5s retries: 5 start_period: 30s # RabbitMQ starts slowly rate-limiter-api: image: rate-limiter-api:1.4.0 healthcheck: test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:4000/health"] interval: 10s timeout: 3s retries: 3 start_period: 15sThe probe runs inside the container, so the tool must exist in that image. Alpine images ship wget through BusyBox but usually not curl. Use CMD when you can run the binary directly, and CMD-SHELL when you need a shell feature such as || or a pipe.
How to Gate Startup with service_healthy
services: api: build: . depends_on: postgres: condition: service_healthy redis: condition: service_healthy rabbitmq: condition: service_healthy migrate: condition: service_completed_successfully migrate: build: . command: ["npm", "run", "migrate"] depends_on: postgres: condition: service_healthy restart: "no"The migrate service runs once, exits with code 0, and only then does the API start. If a dependency has no healthcheck defined, service_healthy cannot be satisfied and Compose reports an error.
How to Wait for the Whole Stack from a Script
docker compose up -d --wait # Give slow stacks more timedocker compose up -d --wait --wait-timeout 120--wait uses the same health definitions as depends_on, so scripts and CI share one readiness contract instead of hand-written polling loops.
How to Read Health Status
docker compose ps# NAME STATUS# stack-postgres-1 Up 15 seconds (healthy)# stack-rabbitmq-1 Up 15 seconds (health: starting)# stack-api-1 Created # Full health record with recent probe outputdocker inspect stack-rabbitmq-1 --format '{{json .State.Health}}' | jq # Just the last probe's outputdocker inspect stack-rabbitmq-1 --format '{{(index .State.Health.Log 0).Output}}' # Watch the state change livedocker events --filter event=health_statusHow to Debug a Health Check That Never Turns Healthy
# 1. Is the probe binary present in the image?docker compose exec rate-limiter-api which wget # 2. Is the app listening on the expected port?docker compose exec rate-limiter-api netstat -tln # 3. Run the exact probe by hand and check the exit codedocker compose exec rate-limiter-api wget --no-verbose --tries=1 --spider http://localhost:4000/healthecho $? # 4. Read the application's startup logsdocker compose logs rate-limiter-api --tail=50How to Use wait-for-it.sh When You Are Outside Compose
Health checks coordinate containers inside Compose. When a plain script on a CI runner must wait for a port, wait-for-it.sh is still useful.
curl -o wait-for-it.sh https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.shchmod +x wait-for-it.sh./wait-for-it.sh localhost:5432 --timeout=30 -- npm run test:integrationIt only proves a TCP port is open, not that the application works, so prefer docker compose up --wait whenever the services have health checks.
Production Best Practices & Common Pitfalls
- Use lightweight probes:
pg_isreadyandredis-cli pingare cheap. A heavy database query every two seconds adds load for no benefit. - Set
start_periodfrom measurements: about 10 to 20 seconds for databases and 30 seconds for RabbitMQ or Elasticsearch, shorter for simple HTTP services. - Avoid aggressive intervals and timeouts: a healthy but briefly slow service gets marked unhealthy and pushes load to its neighbours.
- Keep
/healthminimal: return200or503and nothing else. Do not expose versions or connection details. - Make the app resilient anyway: because Compose checks dependencies only at startup, your code should retry connections after a database restart.
- Use
service_completed_successfullyfor migrations: it is clearer and safer than starting migrations inside the API entrypoint.
TipPrefer
docker compose up -d --waitin scripts and CI. It removes custom polling loops and guarantees the same readiness rules everywhere.
Remember
wait-for-it.shchecks that a port is open, while a health check proves the application works. A database port can be open while the database is still recovering.
Common MistakeWriting
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]on an Alpine image without curl. The probe fails with "executable file not found" and the service is never healthy. Usewget --spideror install curl in the Dockerfile.
SecurityAn unauthenticated
/healthendpoint that returns dependency details leaks internal information. Return a bare status code and keep diagnostics in logs and metrics.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
docker compose ps |
Show health state for each service |
docker compose up -d --wait |
Start and block until healthy |
docker inspect <name> --format '{{json .State.Health}}' |
Full health record |
docker compose exec <svc> <probe command> |
Run the probe by hand |
docker events --filter event=health_status |
Watch health transitions |
docker compose logs -f <svc> |
Read startup logs |
| Problem | Likely cause | Fix |
|---|---|---|
| API crash loop on boot | Dependency not ready | Add service_healthy and a healthcheck |
Stays starting forever |
Probe command missing or wrong port | Run the probe manually inside the container |
| Marked unhealthy during startup | No start_period |
Set it to cover real startup time |
service_healthy error |
Dependency has no healthcheck | Define one on the dependency |
| Flapping healthy/unhealthy | Timeout or interval too tight | Increase timeout and retries |