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.
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
curlin 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
- Build a layered image for a Spring Boot app
- Build a production image for a Node.js service
- Build a production image for a Python web app
- Build, cache and push images in GitHub Actions
- Build one image tag for amd64 and arm64
- Configure nginx from environment variables
- Develop with Compose and live reload
- Make containers cope with dependencies that start slowly