Docker cookbook · Beginner

Add a healthcheck to an HTTP service

Let Docker and Compose know when a container is actually ready and when it has become unhealthy.

Create a free account to save this page, take notes and track your progress. Sign in

Approach

Expose a cheap /health endpoint and declare a HEALTHCHECK that calls it with a tool present in the image. In Compose, other services can wait for service_healthy.

Solution

FROM nginx:1.29-alpine
COPY site/ /usr/share/nginx/html/
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=3 \
  CMD wget -qO- http://127.0.0.1/health || exit 1

Pitfalls

  • Using curl in an image that doesn't contain it.
  • Health endpoints that check every dependency, marking the app unhealthy during a database blip.
  • Expecting plain Docker to restart unhealthy containers; it doesn't (orchestrators do).

Variations

  • In distroless images, build a tiny health binary into the image or rely on the orchestrator's HTTP probes.
  • Separate liveness and readiness endpoints for Kubernetes.

Further reading: HEALTHCHECK

Reference: https://docs.docker.com/reference/dockerfile/#healthcheck

More Docker recipes

Was this page helpful?