Skip to main content

Docker Health Check

A Docker health check is a HEALTHCHECK instruction or docker run flag that runs a command inside a container on a schedule to decide if it is healthy. A container's health status is starting, healthy, or unhealthy.

Running is not the same as working

By default Docker only knows whether the main process is alive. An app can be running yet deadlocked, or still warming up. A health check runs a probe, and exit code 0 means healthy while exit code 1 means unhealthy. After the configured number of consecutive failures the status becomes unhealthy.

stateDiagram-v2 [*] --> starting starting --> healthy: probe exits 0 starting --> unhealthy: retries exhausted healthy --> unhealthy: consecutive failures unhealthy --> healthy: probe exits 0

In a Dockerfile

Dockerfile
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
CMD curl -f http://localhost:8080/health || exit 1
# No curl in the image? Use wget (present in many Alpine images)
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1

Probes for common services

Dockerfile
HEALTHCHECK CMD pg_isready -U postgres -d payments || exit 1
HEALTHCHECK CMD redis-cli ping | grep -q PONG || exit 1
HEALTHCHECK CMD mysqladmin ping -h localhost || exit 1

Inspect status

Bash
docker ps
# payment-api Up 5 minutes (healthy)
docker inspect payment-api --format '{{json .State.Health}}' | jq
docker events --filter event=health_status

What reacts to health

Plain Docker records the status but does not restart on it. Compose can wait on it with depends_on conditions, Swarm replaces unhealthy tasks, and Kubernetes ignores the Docker HEALTHCHECK and uses its own probes instead.

Tip

Set start_period to cover real startup time so warm-up failures do not count against retries.

Common Mistake

Aggressive intervals and timeouts. A healthy but briefly slow service gets marked unhealthy and removed from rotation, increasing load on the rest.

Frequently Asked Questions

How is a health check different from checking if the process is running?

Process status says only that the main process has not exited. A health check runs a real probe, such as an HTTP request or pg_isready, so it can detect hangs, lost database connections, and apps that have not finished starting.

Does an unhealthy status restart my container?

Not in plain Docker. The status is informational there. Swarm and some external tools act on it, and Compose can use it for startup ordering, but a restart policy only reacts to the process exiting.

Does Kubernetes use the Dockerfile HEALTHCHECK?

No. Kubernetes ignores it and relies on liveness, readiness, and startup probes defined in the pod spec.

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