Skip to content
Lesson: Health ChecksSwitch
← DevOps Operations

Delivery and containers

Health Checks

Check that a deployed service really works, not just that its process is running.

A process can be running and still be useless: stuck, misconfigured or unable to reach its database. A health check asks the service to prove it works.

An HTTP check

Many services offer an address for this, often /health. The name is a convention, and your application must implement it.

bash
curl -fsS -m 5 http://localhost:8080/health; echo "exit=$?"
ok
exit=0

-m 5 limits the whole request to five seconds. -f turns HTTP responses of 400 and above into a failing exit status. Without it, curl normally exits 0 even for an error page.

Liveness and readiness

Two different questions:

  • Liveness: is the program stuck and in need of a restart?
  • Readiness: can it take requests right now?

A service that is still loading data may be alive but not ready. Kubernetes has separate liveness and readiness probes: a failing liveness probe restarts the container, while a failing readiness probe stops it receiving Service traffic. Be careful about making liveness depend on a database, or an outage can cause pointless restarts.

Docker health checks

A Dockerfile can define one (the image must contain the tool used, here curl):

dockerfile
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
  CMD curl -f http://localhost:8080/health || exit 1

The container starts as starting, becomes healthy after a successful check, and becomes unhealthy after three failures in a row. Check it:

bash
docker inspect --format '{{.State.Health.Status}}' shop
healthy

Plain Docker Engine only records the status. It does not restart a container just because it is unhealthy. --start-period gives a slow program time before failures count against it.

Use checks during deploys

Wait for the new version to pass before sending it traffic or removing the old one. Retry a few times, because startup takes a while, but give up eventually:

bash
curl -fsS --retry 5 --retry-delay 2 --retry-connrefused http://localhost:8080/health

Try it

Run python3 -m http.server 8080 --bind 127.0.0.1 in one terminal. In another, run curl -fsS -o /dev/null http://localhost:8080/; echo $?, then request /missing and compare. Stop the server and try again. The processes and cron lab helps with finding and stopping processes.

Check your understanding

Health Checks

All 3 sections · no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.