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
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_healthyintervalis how often the probe runs.timeoutis how long one probe may take before it counts as a failure.retriesis the number of consecutive failures before the container is unhealthy.start_periodgives slow starters a grace period where failures do not count.
Probe examples
# Redishealthcheck: test: ["CMD", "redis-cli", "ping"]# HTTP service with curl in the imagehealthcheck: test: ["CMD", "curl", "-f", "http://localhost:8080/health"]# MongoDBhealthcheck: test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]Check status
docker compose ps# postgres Up 2 minutes (healthy)docker inspect --format '{{json .State.Health}}' <container> | jqCommon MistakeUsing
depends_on: [postgres]alone and assuming it waits for readiness. Addcondition: service_healthyand a realhealthcheck.
TipThe 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.