Skip to main content

Compose Health Check

A Compose health check is a healthcheck block on a service that runs a probe command on a schedule to decide whether the container is healthy. Other services use depends_on with condition: service_healthy to wait for readiness.

Started is not ready

A container can be running while the program inside is still initialising. PostgreSQL, for example, needs a few seconds after start before it accepts connections. Plain depends_on only waits for the dependency container to start, so an API can race ahead, fail to connect, and crash. A health check gives Compose a real readiness signal.

Configuration

YAML
services:
postgres:
image: postgres:16-alpine
environment:
POSTGRES_PASSWORD: devpassword
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 5
start_period: 10s
payment-api:
image: payment-api:v3.1.0
depends_on:
postgres:
condition: service_healthy
  • interval is how often the probe runs.
  • timeout is how long one probe may take before it counts as a failure.
  • retries is the number of consecutive failures before the container is unhealthy.
  • start_period gives slow starters a grace period where failures do not count.

Probe examples

YAML
# Redis
healthcheck:
test: ["CMD", "redis-cli", "ping"]
# HTTP service with curl in the image
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
# MongoDB
healthcheck:
test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]

Check status

Bash
docker compose ps
# postgres Up 2 minutes (healthy)
docker inspect --format '{{json .State.Health}}' <container> | jq
Common Mistake

Using depends_on: [postgres] alone and assuming it waits for readiness. Add condition: service_healthy and a real healthcheck.

Tip

The probe runs inside the container, so the tool it uses (curl, wget, pg_isready) must exist in that image.

Frequently Asked Questions

What does condition: service_healthy actually wait for?

It makes Compose hold the dependent service until the dependency's health check reports healthy. If the dependency has no healthcheck defined, the condition cannot be satisfied and Compose reports an error.

Why does my service flip to unhealthy during startup?

Failures during start_period are ignored, but without it normal warm-up failures count toward retries. Set start_period to cover your realistic startup time.

Does a failing health check restart the container?

Not by itself. Plain Docker and Compose only record the unhealthy status. A restart policy reacts to the process exiting, not to health status, so an orchestrator or an external tool must act on unhealthy containers.

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