Chapter 2 · Lesson 9 of 20
Docker

Docker healthcheck: add HEALTHCHECK and read container health

A Docker healthcheck is a command Docker runs inside a container on a schedule to decide whether the app is healthy, which is a stronger claim than running.

By the end you will

Add a healthcheck to a container and read its healthy or unhealthy status.

Time
20 min
Level
Beginner
Check
4 questions
You need
  • Docker installed
  • An image or service with a web endpoint to test

A Docker healthcheck is a command Docker runs inside a container every few seconds; exit code 0 marks the container healthy and repeated failures mark it unhealthy. It tells you the app answers, which Up alone does not. Plain Docker only reports the status, so something else has to act on it.

How it works#

Docker runs the healthcheck command inside the container on a schedule. The command’s exit code decides the result: 0 means healthy, 1 means unhealthy (2 is reserved, so do not use it). Each container with a healthcheck has one of three states:

StateMeaning
startingNo check has passed yet, or the container is within its start_period
healthyThe latest check passed
unhealthyThe check failed retries times in a row

The options are interval (time between checks, 30 seconds by default), timeout (how long one check may run before it counts as failed, 30 seconds by default), retries (consecutive failures before unhealthy, 3 by default) and start_period (boot time during which failures are not counted).

The status is information. Plain Docker does not restart an unhealthy container. What reads the status: docker ps, Compose (depends_on with condition: service_healthy), orchestrators such as Docker Swarm, and monitoring tools. A restart policy reacts to the process exiting, not to a failing health status.

A worked example, start to finish#

Take the Compose service from step 2 with interval: 30s, retries: 3 and start_period: 10s.

  1. The container starts and the status is starting.
  2. For the first 10 seconds, failed checks do not count. The first successful check flips the status to healthy.
  3. Later the app hangs. Each check times out and fails. After three failures in a row the status becomes unhealthy.
  4. docker ps shows (unhealthy). Nothing is restarted. A monitor, a deploy script or depends_on in Compose can now react.
  5. When the app recovers, the next successful check sets the status back to healthy.

The status is the only thing the check changes. What you do with it is up to you.

Step 1: Add HEALTHCHECK to a Dockerfile#

dockerfile
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD wget -q --spider http://localhost:3000/ || exit 1

The command must exit 0 for healthy and 1 for unhealthy. The tool you call has to exist inside the image. Alpine based images such as node:22-alpine include a small wget, but not curl, which is why this example uses wget.

Step 2: Or use Compose#

yaml
services:
  web:
    image: hello-node
    healthcheck:
      test: ["CMD", "wget", "-q", "--spider", "http://localhost:3000/"]
      interval: 30s
      timeout: 3s
      retries: 3
      start_period: 10s

start_period gives a slow app time to boot before failures count. A Compose healthcheck overrides any HEALTHCHECK baked into the image. Use ["CMD-SHELL", "..."] instead of CMD when you need shell features such as ||.

A database example that other services can wait for:

yaml
services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: change-me
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 10
  app:
    image: hello-node
    depends_on:
      db:
        condition: service_healthy

Step 3: Read the status#

bash
docker ps
docker inspect --format '{{json .State.Health}}' web

What you should see: in docker ps, the STATUS column reads Up ... (health: starting), then Up ... (healthy) once the command succeeds. The inspect command prints JSON with a Status field and a Log of recent check results, with start and end times, exit codes and output.

Check it worked#

Start the container, wait a few seconds, then run docker ps: STATUS ends in (healthy). To see a failure, point the check at a path that does not exist, rebuild, and watch the status become (unhealthy) after the retries. The Log in the inspect output shows the failing output and an exit code of 1.

Edge cases and gotchas#

  • The check runs inside the container. Use localhost and the container’s own port, not the published host port. A mapping like 8080:3000 means nothing inside the container.
  • The tool must exist in the image. Slim and distroless images may have neither curl nor wget. The log says the executable file was not found. Install a tool, or use one the app already ships.
  • localhost can resolve to IPv6. Some tools try ::1 first, and an app listening only on IPv4 refuses it. If a check fails but the app works, try 127.0.0.1 in the check.
  • A port check is a weak check. “The port is open” does not mean the app works. Have the check call a small health endpoint that touches what the app depends on, but keep it cheap.
  • Slow boots look like failures. Without start_period, a slow app can be marked unhealthy while still starting. Set it a bit longer than the usual boot.
  • Unhealthy does not mean restarted. With plain docker run or Compose, nothing restarts it. Add monitoring, or an orchestrator, if you want action.
  • Checks use CPU. A heavy command every few seconds adds load on a small server. Keep intervals reasonable.

Troubleshooting#

SymptomLikely causeFix
Stays unhealthy, log says the executable file was not foundThe tool is missing in the imageInstall it in the Dockerfile, or use another tool
Unhealthy, but the app works from outsideThe check used the published host portUse localhost and the container port
Stays in startingThe check never succeeds, or start_period is longRead .State.Health.Log
Marked unhealthy during bootThe app is slow to startAdd or extend start_period
dependency failed to start: container app-db-1 is unhealthyThe database never became healthyCheck docker logs db and the check command
Check passes but the app is brokenThe check is too shallowCheck a real endpoint instead of only the port
Quoting errors in the Compose testShell syntax in CMD formUse CMD-SHELL
Status is starting for a long timeThe first check has not succeeded, or start_period is longRead .State.Health.Log for the exit code and output
Healthy container, broken appThe check only tests that a port is openPoint it at an endpoint that touches the database

Real-world scenario#

A Node app loses its database connection pool after a network blip. The process keeps running, so docker ps says Up and the restart policy does nothing, while every request fails. The blog guide A health check can pass on a dead container covers this trap.

You add a /healthz endpoint that runs a trivial query, and a healthcheck that calls it with wget. Now docker ps shows (unhealthy) within a minute and a small uptime monitor sends an alert. You also use depends_on with service_healthy so the app never starts before Postgres is ready.

Quick reference#

ItemValue
DockerfileHEALTHCHECK --interval=30s --timeout=3s --retries=3 CMD wget -q --spider http://localhost:3000/ || exit 1
Compose keyhealthcheck: with test, interval, timeout, retries, start_period
Shell form in Composetest: ["CMD-SHELL", "pg_isready -U postgres"]
Read statusdocker ps, docker inspect --format '{{json .State.Health}}' NAME
Wait for healthdepends_on: with condition: service_healthy
Statesstarting, healthy, unhealthy

Next#

Pass settings to your services in Docker Compose environment variables.

Check what you learned4 questions
1A container shows (unhealthy) but the app works from outside. What is the likely mistake?
2Why might a healthcheck using curl fail on a slim image?
3What does retries=3 mean?
4A slow app needs 40 seconds to boot and is marked unhealthy before it is ready. Which option helps?

Frequently asked questions

Does an unhealthy container get restarted automatically?

Not by plain Docker. The status is only reported. Orchestrators and tools that watch health can act on it, and in Compose you can make one service wait for another to be healthy.

Why is my healthcheck always failing?

Often the command is missing from the image. Slim images may not include curl or wget, so install one or use a tool that is already there.

How do I make the app wait for the database to be healthy?

Give the database a healthcheck, then in the app service use depends_on with condition service_healthy. Compose then starts the app only after the database reports healthy.

Does a healthcheck slow my app down?

The command runs on a schedule inside the container, so a heavy command every few seconds can use real CPU. Keep it light and set a sensible interval.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios