Last updated: November 25, 2026.
A container can be running and still be useless. The process exists, but the app may be waiting on a database, missing a dependency, returning 500s, or listening on the wrong port.
A Docker Compose healthcheck solves that gap. It runs a command inside the container and records whether the service is starting, healthy, or unhealthy. The best checks are small, local, and tied to the thing the service must do before another container depends on it.
Add a healthcheck block with test, interval, timeout, retries, and start_period. Use depends_on with condition: service_healthy when another service must wait for readiness. Then use docker compose ps and docker inspect to read the status and the last healthcheck output.
services: api: build: ./api healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8080/health"] interval: 30s timeout: 5s retries: 3 start_period: 20sWhat Are Docker Compose Health Checks
Docker Compose health checks are commands that Docker runs inside a service container to test whether the application is ready. Docker Compose is Docker’s tool for defining and running multi-container applications from a Compose file; a healthcheck adds an application-level readiness signal to one service in that file.
That distinction matters. docker compose up can start a database container before the database accepts connections. It can start an API container before the API has loaded config. A healthcheck lets Docker record the difference between “the process started” and “the service can do useful work.”
Docker’s Compose file reference documents the healthcheck fields under service definitions, and the Dockerfile reference documents the same timing concepts for image-level HEALTHCHECK instructions. Compose can also disable an image’s baked-in healthcheck with disable: true or test: ["NONE"] when the image default does not fit your local stack.
When a container is already marked unhealthy, start with the failing command and its output. Our guide to Docker status unhealthy walks through that debugging path.
Quick Start: A Common Health Check Pattern
For an HTTP service, start with a dedicated endpoint such as /health, /healthz, or /ready. The endpoint should return a 2xx status when the service can handle the work its dependents need.
services: api: image: my-api:latest healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8080/healthz"] interval: 30s timeout: 5s retries: 3 start_period: 20sIn a Compose healthcheck, localhost means the container running the check. It does not mean your laptop, and it does not mean another service on the Compose network. If your API listens on port 8080 inside the container and you publish it as 3000:8080, the healthcheck should still call http://localhost:8080/healthz.
Make sure the image includes the tool you call. Alpine and distroless-style images often do not include curl.
FROM nginx:alpineRUN apk add --no-cache curlIf you do not want to install curl, use a tool already present in the image. BusyBox wget is common in Alpine-based images:
healthcheck: test: ["CMD-SHELL", "wget -qO- http://localhost:8080/healthz >/dev/null || exit 1"] interval: 30s timeout: 5s retries: 3Set Up Your First Docker Compose Health Check
Use compose.yaml for new projects. Compose prefers that file name and still accepts docker-compose.yml.
services: web: image: nginx:alpine ports: - "8080:80" healthcheck: test: ["CMD", "curl", "-f", "http://localhost"] interval: 30s timeout: 5s retries: 3 start_period: 10sThe test command decides the result:
- exit code
0: the check passed - non-zero exit code: the check failed
Docker records one of three health states:
| Status | Meaning |
|---|---|
starting | The container is inside its startup window, or it has not passed enough checks yet. |
healthy | The healthcheck command returned success. |
unhealthy | The command failed enough times to cross the configured retries threshold. |
Use CMD for a command expressed as an argument array. Use CMD-SHELL when you need shell features such as pipes, variable expansion, &&, or ||.
# No shell neededhealthcheck: test: ["CMD", "redis-cli", "ping"]
# Shell needed for env vars and fallback logichealthcheck: test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} || exit 1"]The doubled dollar sign ($${POSTGRES_USER}) keeps Compose from interpolating the variable on the host. The container shell receives ${POSTGRES_USER} and expands it inside the container.
Health Check Options Explained
Docker Compose supports the same main healthcheck timing fields used by Docker healthchecks. Keep these values boring until you have a reason to tune them.
| Option | What it controls | Typical starting point |
|---|---|---|
test | Command Docker runs inside the container | Service-specific command |
interval | Time between healthcheck runs | 30s |
timeout | How long Docker waits before a single check fails | 5s to 10s |
retries | Consecutive failures before unhealthy | 3 |
start_period | Startup grace period before failures count | 10s to 60s |
start_interval | Check cadence during the startup period, when supported | Shorter than interval |
start_period is the setting that prevents slow-starting services from being marked unhealthy too early. Use it for databases, JVM services, search engines, and apps that run migrations during startup.
Avoid long intervals unless the check is only informational. A one-hour interval can leave a broken local dependency looking healthy long after it stopped serving traffic. If the service gates another container, use an interval short enough to catch readiness during startup.
Health Check Commands for Common Services
Healthchecks should test the service from inside its own container. Use localhost for the same container; use a Compose service name only when a different container is intentionally testing a dependency.
HTTP APIs
healthcheck: test: ["CMD", "curl", "-f", "http://localhost:3000/health"] interval: 30s timeout: 5s retries: 3 start_period: 20sUse /healthz or /ready if your app exposes Kubernetes-style endpoints.
healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8080/healthz"]Alpine Nginx
services: nginx: image: nginx:alpine ports: - "8080:80" healthcheck: test: ["CMD-SHELL", "wget -qO- http://localhost/ >/dev/null || exit 1"] interval: 30s timeout: 5s retries: 3 start_period: 10sThis matches a common local setup: a small Nginx container with a healthcheck but no extra curl install.
PostgreSQL
services: postgres: image: postgres:16 environment: POSTGRES_USER: app POSTGRES_PASSWORD: example POSTGRES_DB: appdb healthcheck: test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] interval: 10s timeout: 5s retries: 5 start_period: 20spg_isready checks whether Postgres accepts connections. If your app requires migrations before startup, gate the app on a one-shot migration job too; do not overload the Postgres healthcheck with app-specific work.
MySQL
services: mysql: image: mysql:8 environment: MYSQL_DATABASE: appdb MYSQL_USER: app MYSQL_PASSWORD: example MYSQL_ROOT_PASSWORD: root-example healthcheck: test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -u$${MYSQL_USER} -p$${MYSQL_PASSWORD} --silent"] interval: 10s timeout: 5s retries: 5 start_period: 30sUse 127.0.0.1 if you want to force TCP instead of a local socket path.
Redis
services: redis: image: redis:7 healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 10s timeout: 3s retries: 3For password-protected Redis, include auth in the command and keep secrets out of the Compose file when possible.
healthcheck: test: ["CMD-SHELL", "redis-cli -a $${REDIS_PASSWORD} ping | grep PONG"]MongoDB
services: mongo: image: mongo:7 healthcheck: test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping').ok"] interval: 10s timeout: 5s retries: 5 start_period: 30sIf auth is enabled, pass the user, password, and authentication database explicitly.
RabbitMQ
services: rabbitmq: image: rabbitmq:3-management healthcheck: test: ["CMD", "rabbitmq-diagnostics", "check_port_connectivity"] interval: 10s timeout: 5s retries: 5 start_period: 30sRabbitMQ can take time to initialize plugins. Give it a realistic start_period before dependent services wait on it.
Check Docker Compose Health Status
Use docker compose ps for the fast status view:
docker compose psFor a service with a healthcheck, the STATUS column adds the health state to the uptime:
NAME SERVICE STATUSapp-api-1 api Up 9 seconds (healthy)app-db-1 db Up 9 seconds (health: starting)app-web-1 web Up 9 seconds (unhealthy)For script-friendly output, use the Docker Compose ps formatting option documented in the CLI reference:
docker compose ps --format jsonCurrent Compose versions print one JSON object per container, one per line. State holds the lifecycle state (running), and Health holds healthy, unhealthy, or starting. That makes a quick per-service health check a one-liner:
docker compose ps --format json | jq -r '"\(.Service) \(.Health)"'If you need the healthcheck log and failing streak, inspect the container directly:
docker inspect --format='{{json .State.Health}}' <container_name> | jqThat output includes the current health status, the failing streak, and recent healthcheck runs with exit codes and command output. It is the most useful command when docker compose ps only tells you that something is unhealthy.
You can also filter containers by health with Docker:
docker ps --filter health=unhealthyFor starting, check whether the service is still inside start_period or whether the check has never passed. For unhealthy, run the healthcheck command manually inside the container:
docker compose exec api sh -lc 'curl -f http://localhost:8080/healthz'Coordinate Service Startup with Health Checks
depends_on controls startup and shutdown order. By default, it only waits for a container to start. To wait for readiness, combine it with a healthcheck and condition: service_healthy, as documented in the Compose depends_on reference.
services: db: image: postgres:16 environment: POSTGRES_USER: app POSTGRES_PASSWORD: example POSTGRES_DB: appdb healthcheck: test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] interval: 10s timeout: 5s retries: 5 start_period: 20s
api: build: ./api depends_on: db: condition: service_healthyThis prevents the API container from starting until Postgres reports healthy. It does not mean the database is semantically ready for every application operation. If your API needs migrations, seed data, or a warmed cache, represent that work directly.
Health status tells you whether the container’s probe passed. Logs tell you why it failed. Use the Docker Compose logs guide when the healthcheck output points to a startup or dependency error.
Handle Complex Service Dependencies in Docker Compose
Compose supports three dependency conditions in the long depends_on syntax:
| Condition | Use it when |
|---|---|
service_started | The dependent only needs the container process to start. |
service_healthy | The dependent needs a long-running service to pass its healthcheck. |
service_completed_successfully | The dependent needs a one-shot job to exit with status 0. |
Use service_completed_successfully for migrations, setup jobs, test jobs, and other containers that should finish rather than stay running.
services: db: image: postgres:16 environment: POSTGRES_USER: app POSTGRES_PASSWORD: example POSTGRES_DB: appdb healthcheck: test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] interval: 10s timeout: 5s retries: 5 start_period: 20s
migrate: image: flyway/flyway:latest command: -url=jdbc:postgresql://db:5432/appdb -user=app -password=example migrate depends_on: db: condition: service_healthy
api: build: ./api depends_on: db: condition: service_healthy migrate: condition: service_completed_successfullyDo not use service_completed_successfully for APIs, databases, queues, or workers that should keep running. Those services should usually expose a healthcheck and be gated with service_healthy.
Circular dependencies are a design smell in Compose. If two services need each other to start, split the bootstrap path. Start one service in a reduced mode, move one-time setup into a job, or remove the startup-time callback.
Advanced Health Check Techniques
A good Docker Compose healthcheck is cheap, deterministic, and local to the container. It should fail when the service cannot do its core job, but it should not create new load or mutate production data.
Custom Health Endpoints
Application-owned endpoints work well because the app knows its own readiness rules.
app.get("/healthz", async (req, res) => { try { await db.query("SELECT 1"); await redis.ping(); res.status(200).json({ status: "ok" }); } catch (err) { res.status(503).json({ status: "unhealthy", reason: err.message }); }});Then call that endpoint from the service’s healthcheck:
healthcheck: test: ["CMD", "curl", "-f", "http://localhost:3000/healthz"] interval: 30s timeout: 5s retries: 3Keep the endpoint fast. If it calls every dependency and an upstream API, the healthcheck becomes a source of noise and load.
Shell Checks
Use shell checks when one command needs fallback logic.
healthcheck: test: ["CMD-SHELL", "curl -fsS http://localhost:8080/healthz || wget -qO- http://localhost:8080/healthz >/dev/null"] interval: 30s timeout: 5s retries: 3Shell checks are also useful for combining a process check and a local endpoint, but keep them readable. If the line grows past one or two commands, move it into a script and test that script in CI.
Functional Checks
Functional checks test a real workflow. Use them sparingly in Compose healthchecks because they can mutate data, create load, and fail for reasons unrelated to container readiness.
A safe version checks a read-only path:
#!/usr/bin/env shset -eucurl -fsS http://localhost:8080/healthz >/dev/nullcurl -fsS http://localhost:8080/api/version >/dev/nullAvoid checks that create users, send messages, delete records, or call paid external APIs. Put those in smoke tests, not in a healthcheck that runs every few seconds.
Health Checks in a Multi-Service Docker Compose Stack
Here is a complete local stack with Postgres, Redis, an API, and an Nginx frontend. It uses healthchecks for the long-running services and startup gates for dependencies.
services: db: image: postgres:16 environment: POSTGRES_USER: app POSTGRES_PASSWORD: example POSTGRES_DB: appdb healthcheck: test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] interval: 10s timeout: 5s retries: 5 start_period: 20s
redis: image: redis:7 healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 10s timeout: 3s retries: 3
api: build: ./api depends_on: db: condition: service_healthy redis: condition: service_healthy healthcheck: test: ["CMD", "curl", "-f", "http://localhost:3000/healthz"] interval: 30s timeout: 5s retries: 3 start_period: 20s
web: image: nginx:alpine ports: - "8080:80" depends_on: api: condition: service_healthy healthcheck: test: ["CMD-SHELL", "wget -qO- http://localhost/ >/dev/null || exit 1"] interval: 30s timeout: 5s retries: 3 start_period: 10sAfter startup, check the stack:
docker compose psdocker compose ps --format jsonIf a service is unhealthy, inspect its recent check history:
docker inspect --format='{{json .State.Health}}' $(docker compose ps -q api) | jqThis combination gives you the high-level status and the command-level failure detail.
Troubleshooting Health Checks in Docker Compose
Most false failures come from command context, missing tools, timing, or the wrong port.
| Symptom | Likely cause | What to do |
|---|---|---|
curl: not found | Minimal image does not include curl | Install curl, use wget, or use a service-native CLI. |
connection refused | App is not listening yet, or listens on another port | Check app logs and test the same command with docker compose exec. |
| Works on host, fails in healthcheck | localhost means different things | Use the container’s internal port and run the command inside the container. |
Stuck in starting | start_period is too long, or the check never passes | Inspect .State.Health and run the command manually. |
| Flaps between healthy and unhealthy | Timeout too short, endpoint too heavy, or service overloaded | Raise timeout, simplify the endpoint, and inspect resource usage. |
| Dependent service starts too early | depends_on uses the default service_started | Use condition: service_healthy and add a real healthcheck to the dependency. |
Test the exact command manually:
docker compose exec api sh -lc 'curl -f http://localhost:3000/healthz'Then inspect health history:
docker inspect --format='{{json .State.Health}}' $(docker compose ps -q api) | jqIf you need broader container troubleshooting, pair health status with logs and lifecycle state. The guides on Docker logs and Docker container lifecycle cover those parts of the debugging loop.
FAQ
How do you check Docker Compose health status?
Run docker compose ps to see each service state. For healthcheck history and output, run docker inspect --format='{{json .State.Health}}' <container_name> and inspect the Status, FailingStreak, and Log entries.
Can a Docker Compose healthcheck use localhost?
Yes, when the service listens inside the same container. In a healthcheck, localhost means the container itself, not your host machine and not another Compose service.
What is a good Docker Compose healthcheck example for PostgreSQL?
Use pg_isready inside the Postgres container, for example test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] with a short interval, timeout, retries, and a start_period that matches your startup time.
When should you use service_completed_successfully?
Use service_completed_successfully for one-shot containers such as migrations, schema setup, or test jobs that must exit with code 0 before another service starts. Do not use it for long-running APIs or databases.
What happens when a Docker Compose healthcheck fails?
After the configured number of retries, Docker marks the container unhealthy, but it keeps running. Docker does not restart unhealthy containers, even with restart: always; restart policies only act when the process exits. Services that depend on it with condition: service_healthy are not started, and docker compose up fails with dependency failed to start: container <name> is unhealthy.
What does start_period do in a Docker Compose healthcheck?
start_period gives a service time to initialize before failed healthchecks count toward the retry limit. Use it for databases, JVM apps, search nodes, or services that run startup migrations.
A Short Healthcheck Checklist
Start with one cheap local check per service. Use service-native commands for databases and queues, HTTP readiness endpoints for APIs, and depends_on conditions only where startup order matters.
Before you call a Compose stack ready, verify three things: docker compose ps shows the status you expect, docker inspect shows useful healthcheck output, and a fresh docker compose up starts dependents only after their prerequisites are ready.
For production troubleshooting, Compose health status is only one signal. Keep it next to logs, metrics, and traces so you can see why a service became unhealthy, not just that the probe failed.
