Skip to main content

Configuring Docker Compose Health Checks

Configure Docker Compose health checks and depends_on service_healthy so apps start only after databases and queues are ready.

44 Terms

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_on guarantees start order but not readiness.
  • Write health checks for PostgreSQL, Redis, RabbitMQ, and an HTTP service.
  • Gate startup with service_healthy and use docker compose up --wait.
  • Read health states and debug a check that never turns healthy.
  • Know when a script such as wait-for-it.sh is 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.

sequenceDiagram participant C as Compose participant P as postgres participant A as api C->>P: start container P-->>C: status starting C->>P: run pg_isready P-->>C: healthy C->>A: start api now A->>P: connect succeeds

Remember these facts:

  1. Three health states exist: starting, healthy, and unhealthy. Failures during start_period do not count toward retries.
  2. Exit code decides the result: the probe exits 0 for healthy and 1 for unhealthy.
  3. Three depends_on conditions exist: service_started (default), service_healthy, and service_completed_successfully (for one-shot jobs such as migrations).
  4. Dependencies are checked at startup only. If a database becomes unhealthy later, Compose does not stop or restart the API.
  5. 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
YAML
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: 15s

The 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
YAML
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
Bash
docker compose up -d --wait
# Give slow stacks more time
docker 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
Bash
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 output
docker inspect stack-rabbitmq-1 --format '{{json .State.Health}}' | jq
# Just the last probe's output
docker inspect stack-rabbitmq-1 --format '{{(index .State.Health.Log 0).Output}}'
# Watch the state change live
docker events --filter event=health_status
How to Debug a Health Check That Never Turns Healthy
Bash
# 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 code
docker compose exec rate-limiter-api wget --no-verbose --tries=1 --spider http://localhost:4000/health
echo $?
# 4. Read the application's startup logs
docker compose logs rate-limiter-api --tail=50
How 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.

Bash
curl -o wait-for-it.sh https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh
chmod +x wait-for-it.sh
./wait-for-it.sh localhost:5432 --timeout=30 -- npm run test:integration

It 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_isready and redis-cli ping are cheap. A heavy database query every two seconds adds load for no benefit.
  • Set start_period from 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 /health minimal: return 200 or 503 and 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_successfully for migrations: it is clearer and safer than starting migrations inside the API entrypoint.
Tip

Prefer docker compose up -d --wait in scripts and CI. It removes custom polling loops and guarantees the same readiness rules everywhere.

Remember

wait-for-it.sh checks 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 Mistake

Writing 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. Use wget --spider or install curl in the Dockerfile.

Security

An unauthenticated /health endpoint 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

Resources

Explore More in Docker Compose and Multi-Container Applications

All 6 Topics

Frequently Asked Questions

Is Configuring Docker Compose Health Checks free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Configuring Docker Compose Health Checks topic cover?

Configure Docker Compose health checks and depends_on service_healthy so apps start only after databases and queues are ready.

Found a mistake, an outdated step or a broken link?