Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Docker HEALTHCHECK: Syntax, Intervals, Retries, and Status Monitoring

The four timing flags, why start-period prevents deploy flapping, and the reason Docker reports unhealthy without ever restarting anything.

~5 min readDocker
#Docker#Health Checks#Reliability
3D illustration of container heartbeat monitors emitting glowing green pulse waves with retry counter valves

Quick Summary

HEALTHCHECK tells Docker how to ask a running container "are you actually working?" It runs a command inside the container on a schedule, and the exit code decides the state: 0 healthy, 1 unhealthy, anything else reserved. Docker itself does not restart an unhealthy container — it reports the state, and orchestrators decide what to do with it.

The four timing flags are where the useful configuration lives. --interval sets how often the check runs, --timeout how long one run may take, --start-period how long a fresh container is allowed to fail before the first failure counts, and --retries how many consecutive failures mark it unhealthy. Getting start-period wrong is the single most common cause of a container that flaps on every deploy.

Basic syntax and query signatures

dockerfile
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \ CMD curl -fsS http://127.0.0.1:3000/health || exit 1
dockerfile
# Exec form: no shell, no curl dependency HEALTHCHECK --interval=30s --timeout=3s \ CMD ["/app/healthcheck", "--url", "http://127.0.0.1:3000/health"]
yaml
services: api: healthcheck: test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/health"] interval: 15s timeout: 3s start_period: 30s retries: 3 legacy: healthcheck: disable: true

HEALTHCHECK NONE in a Dockerfile removes a check inherited from the base image; docker run --no-healthcheck does the same at run time. In Compose, healthcheck.disable: true is the modern spelling, and test accepts ["NONE"] for older versions.

Key comparison table

FlagDefaultEffect
--interval30sTime between the start of consecutive checks
--timeout30sMaximum duration of one check before it counts as a failure
--start-period0sGrace window; failures during it do not count
--retries3Consecutive failures before unhealthy
--start-interval5sCheck frequency during start-period (Engine 25+)
StateMeaningWhat acts on it
startingInside start-period (or fewer than retries failures)depends_on: condition: service_started
healthyLast retries runs exited 0Compose service_healthy gate
unhealthyretries consecutive failuresSwarm reschedules, ECS replaces, Compose starts nothing
Check styleNeeds a shellNeeds a toolWorks on distroless
CMD curl -f …Yes (sh)curlNo
CMD wget -qO- …YeswgetNo
CMD ["/app/healthcheck"]NoOnly the app binaryYes
CMD-SHELL "…" (Compose)YesWhatever it callsNo

Practical edge cases and deep dives

1. start-period versus interval × retries

dockerfile
# Broken for a JVM app that takes 45 s to open its port: HEALTHCHECK --interval=10s --timeout=3s --retries=3 CMD curl -fsS http://127.0.0.1:8080/actuator/health # → marked unhealthy at ~30 s, while still booting; Compose aborts dependents

Without start-period, failures begin counting immediately, so a slow boot looks like a failure. The fix is not a longer interval — that just delays detection forever — but an explicit boot window:

dockerfile
HEALTHCHECK --interval=10s --timeout=3s --start-period=60s --retries=3 CMD ...

During start-period the container reports starting; a successful check flips it to healthy early, and only failures after the window count. The window should be a little longer than the p99 boot time you have measured, not a guess.

--timeout must be smaller than --interval, or two checks overlap and the state becomes meaningless. Docker does not prevent the combination; it simply produces confusing results.

2. The check must exist in the image

dockerfile
FROM gcr.io/distroless/static-debian12 COPY --from=build /out/api /api HEALTHCHECK CMD curl -fsS http://127.0.0.1:8080/health || exit 1 # → OCI runtime exec failed: exec: "sh": executable file not found in $PATH

Distroless and scratch images have no sh, so a shell-form check can never run; the container is permanently unhealthy and every dependent service refuses to start. Two ways to fix it properly:

dockerfile
# 1. Exec form, using a binary the image already has HEALTHCHECK CMD ["/api", "healthcheck"] # 2. Add a tiny static checker to the image COPY --from=build /out/healthcheck /healthcheck HEALTHCHECK CMD ["/healthcheck", "http://127.0.0.1:8080/health"]

The second is worth the extra binary: it uses the same HTTP client, TLS settings, and timeouts as the application, so the check fails for the same reasons the app would.

3. What to check, and what not to

dockerfile
# Checks the dependency, not the container: a DB outage marks every API unhealthy HEALTHCHECK CMD pg_isready -h db -U app || exit 1

A healthcheck that includes dependencies turns one failure into a cascade: the database hiccups, every API replica goes unhealthy, and the orchestrator restarts healthy processes. Liveness should answer "is this process able to serve?"; readiness should answer "should traffic reach it?". Docker has only one signal, so keep it shallow — a cheap local endpoint that returns 200 when the process can handle a request, and put dependency checks in your monitoring, not in the container.

Conversely, a check that always returns 0 is worse than none: it produces a green state that means nothing. CMD ["/bin/true"] is a common copy-paste artefact.

4. Health status is observable, not self-healing

bash
docker inspect api --format '{{.State.Health.Status}}' docker inspect api --format '{{json .State.Health}}' | python3 -m json.tool docker events --filter event=health_status --format '{{.Time}} {{.Actor.Attributes.name}} {{.Actor.Attributes.health_status}}'

The State.Health.Log array holds the last few attempts with exit codes and output — the first place to look when a container is unhealthy. docker events gives the transition timeline, which distinguishes "never became healthy" from "healthy for an hour, then failed".

Docker Engine does not restart on unhealthy. Swarm reschedules the task, ECS replaces the task, and Compose simply gates depends_on — so an unhealthy container can sit there indefinitely in a plain docker run setup. If restart-on-failure is the requirement, that is --restart=unless-stopped with the process exiting, not a healthcheck.

5. Kubernetes ignores HEALTHCHECK

Kubernetes runs its own livenessProbe/readinessProbe and does not read the image's HEALTHCHECK. A Dockerfile probe copied into a Kubernetes deployment therefore does nothing, and the reverse — an image with no HEALTHCHECK deployed to Compose — leaves depends_on: service_healthy unable to work. If both targets matter, define the probe in both places and keep the endpoint identical:

yaml
livenessProbe: httpGet: { path: /health, port: 3000 } periodSeconds: 10 timeoutSeconds: 3 failureThreshold: 3 readinessProbe: httpGet: { path: /ready, port: 3000 }

Two endpoints, two questions: /health for "restart me if this fails", /ready for "stop sending traffic". Collapsing them into one endpoint is how a slow database becomes a restart loop.

6. Inheritance: every container from the image gets the check

A HEALTHCHECK in the image applies to every container started from it, including ones that were never meant to be long-running. A migration job that runs for four seconds and exits is judged by a check that could not possibly pass in that time; the exit code is what matters for the job, but the health state and its log noise confuse anyone reading docker ps -a.

Compose overrides the image's check wholesale rather than merging fields, so defining interval without test is invalid, and defining only test keeps Compose's defaults (30s interval, 30s timeout) — not the image's values. Read the effective configuration with docker inspect <container> --format '{{json .Config.Healthcheck}}' before assuming the Dockerfile's timings are in force.

Common mistakes and runtime errors

Error or symptomCauseFix
OCI runtime exec failed: exec: "sh": … not foundShell-form check on a distroless/scratch imageExec form, or ship a checker binary
Container permanently unhealthy, check exits 127curl/wget not installedInstall it, or use the app's own binary
unhealthy during every deployNo start-periodSet it above the p99 boot time
State flaps between healthy and unhealthytimeout close to or above intervaltimeout ≤ half the interval
depends_on: service_healthy never satisfiedDependent has no healthcheck definedAdd one, or use service_started
Healthcheck consumes noticeable CPUExpensive check (DB query, full render) at a short intervalCheap endpoint; longer interval
Restart loop after adding a checkLiveness depends on an external serviceSplit liveness from readiness
HEALTHCHECK NONE has no effectBase image check re-added later, or run flag missingCheck docker inspect for the final config
Kubernetes ignores the Dockerfile checkExpected: K8s uses probesDefine livenessProbe/readinessProbe
docker ps shows (unhealthy) but traffic flowsNothing acts on the state outside an orchestratorAdd restart policy or external monitoring

The practical default for a web service: interval=30s, timeout=3s, start-period tuned to the boot time, retries=3, and a check that hits a local endpoint which does no I/O beyond a cached status. It catches hung processes without inventing outages.

Try matching browser tools

All tools

Small utilities that fit Docker work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Docker guides

More in Docker

All Docker guides

The guides filed next to this one in Docker, in library order.