Linux Labs

Containers: Docker and compose / Stage 8 of 11

docker compose: a stack in one file

Not running Starting usually ~20 s
Leave the lesson

Step 5 of 7 · theory · 4 min

Health checks

The Up status means the process is alive. Here: how to find out it also answers.

The healthcheck key sets a command Docker runs inside the container on a schedule. Exit code 0 means the check passed; several failures in a row make the container unhealthy.

yaml
    healthcheck:
      test: wget -q -O /dev/null http://localhost:8000/ || exit 1
      interval: 5s       # how often to check
      retries: 3         # failures in a row before unhealthy

docker compose ps shows the result: Up 7 seconds (healthy) or Up 15 seconds (unhealthy). localhost in the check is the container itself. Docker does not restart an unhealthy container: it keeps running with the mark.

With a check in place, depends_on can wait for a neighbour's health — condition: service_healthy under the service name. Then up -d starts the dependent service only after the neighbour is Healthy. If the neighbour never becomes healthy, up -d prints dependency failed to start: container … is unhealthy and exits with code 1.

Check yourself 1 question

api's healthcheck failed three times in a row, and ps shows (unhealthy). What will Docker do with the container?

  • A stopped container would be Exited. An unhealthy one stays Up, marked (unhealthy).

  • The restart policy fires when the process exits. Here the process is alive: ps shows Up … (unhealthy), and the restart count does not grow.

  • docker compose up -d re-creates containers, and only after their description changes. Docker itself just marks an unhealthy container.

The healthcheck only sets a mark: the process is alive, and the container keeps running as Up … (unhealthy). ps and depends_on with condition: service_healthy see that mark.

Key points

  • healthcheck is a command inside the container; ps shows the result as (healthy) or (unhealthy).
  • An unhealthy container keeps running: Docker only marks it.
  • depends_on with condition: service_healthy starts a service after its neighbour is healthy.
Ubuntu 24.04
Loading…