Health Checks

A HEALTHCHECK tells Docker how to test whether your app is working so it can report and act on the container's health.

SyntaxHEALTHCHECK [options] CMD command

A running container is not always a healthy container — the process might be up but the app frozen. A health check defines a command Docker runs periodically to test real health.

Defining a check

Use the HEALTHCHECK instruction in a Dockerfile, or a healthcheck block in Compose. The command should exit 0 for healthy and non-zero for unhealthy.

What it enables

  • docker ps shows a health status (starting, healthy, unhealthy).
  • Compose can wait for a service to be healthy before starting dependents.
  • Orchestrators can restart or replace unhealthy containers.

Example

Example · dockerfile
FROM nginx:1.27-alpine

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget -qO- http://localhost/ || exit 1

When to use it

  • A web service Dockerfile includes a HEALTHCHECK so Docker Compose only marks the container healthy after the HTTP endpoint responds.
  • A database container's health check uses pg_isready so dependent services wait for Postgres to fully initialize before connecting.
  • An ops engineer uses docker inspect to see whether a container is healthy, starting, or unhealthy to diagnose startup failures.

More examples

HTTP health check in Dockerfile

Defines a health check that polls /health every 30 seconds, giving the app 10 seconds to start up.

Example · dockerfile
FROM node:20-alpine
WORKDIR /app
COPY . .
RUN npm ci --omit=dev
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD wget -qO- http://localhost:3000/health || exit 1
EXPOSE 3000
CMD ["node", "index.js"]

Check health status of a container

Extracts the current health status and the output of the most recent health check probe.

Example · bash
docker inspect myapp \
  --format '{{.State.Health.Status}}: {{(index .State.Health.Log 0).Output}}'

Override health check at runtime

Overrides the Dockerfile HEALTHCHECK at runtime so you can test different probe commands without rebuilding.

Example · bash
docker run -d \
  --health-cmd='curl -fs http://localhost:3000/ping || exit 1' \
  --health-interval=20s \
  --health-retries=5 \
  --name api \
  myapp:latest

Discussion

  • Be the first to comment on this lesson.