# 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.

URL: https://levelrail.com/learn/docker/docker-healthchecks/
Updated: 2026-11-27

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:

| State | Meaning |
| --- | --- |
| `starting` | No check has passed yet, or the container is within its `start_period` |
| `healthy` | The latest check passed |
| `unhealthy` | The 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](https://levelrail.com/learn/docker/docker-compose-basics/)) (`depends_on` with `condition: service_healthy`), orchestrators such as Docker Swarm, and monitoring tools. A [restart policy](https://levelrail.com/learn/docker/docker-restart-policies/)) 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

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| Stays unhealthy, log says the executable file was not found | The tool is missing in the image | Install it in the Dockerfile, or use another tool |
| Unhealthy, but the app works from outside | The check used the published host port | Use `localhost` and the container port |
| Stays in `starting` | The check never succeeds, or `start_period` is long | Read `.State.Health.Log` |
| Marked unhealthy during boot | The app is slow to start | Add or extend `start_period` |
| `dependency failed to start: container app-db-1 is unhealthy` | The database never became healthy | Check `docker logs db` and the check command |
| Check passes but the app is broken | The check is too shallow | Check a real endpoint instead of only the port |
| Quoting errors in the Compose `test` | Shell syntax in `CMD` form | Use `CMD-SHELL` |
| Status is `starting` for a long time | The first check has not succeeded, or `start_period` is long | Read `.State.Health.Log` for the exit code and output |
| Healthy container, broken app | The check only tests that a port is open | Point 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](https://levelrail.com/blog/health-check-passes-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](https://levelrail.com/learn/deploy-operate/monitor-uptime-simply/)) sends an alert. You also use `depends_on` with `service_healthy` so the app never starts before Postgres is ready.

## Quick reference

| Item | Value |
| --- | --- |
| Dockerfile | `HEALTHCHECK --interval=30s --timeout=3s --retries=3 CMD wget -q --spider http://localhost:3000/ \|\| exit 1` |
| Compose key | `healthcheck:` with `test`, `interval`, `timeout`, `retries`, `start_period` |
| Shell form in Compose | `test: ["CMD-SHELL", "pg_isready -U postgres"]` |
| Read status | `docker ps`, `docker inspect --format '{{json .State.Health}}' NAME` |
| Wait for health | `depends_on:` with `condition: service_healthy` |
| States | `starting`, `healthy`, `unhealthy` |

## Related lessons

- [Docker restart policies](https://levelrail.com/learn/docker/docker-restart-policies/)): restart on exit, which health does not trigger
- [Docker Compose basics](https://levelrail.com/learn/docker/docker-compose-basics/)): where `depends_on` and `healthcheck` live
- [Monitor uptime simply](https://levelrail.com/learn/deploy-operate/monitor-uptime-simply/)): alert when a check fails
- [Read container logs](https://levelrail.com/learn/deploy-operate/read-container-logs/)): find out why a check fails

## Next

Pass settings to your services in [Docker Compose environment variables](https://levelrail.com/learn/docker/docker-compose-environment-variables/)).

## 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

- [Docker docs, Dockerfile reference](https://docs.docker.com/reference/dockerfile/)
