Docker & Containers (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
How do you implement Docker health checks (`HEALTHCHECK`) and how do orchestrators consume them?
senior LevelMost AskedCode ExampleDocker & ContainersSystem Design
In Simple Words:
By default, Docker only checks if PID 1 is alive. If your web server deadlocks, exhausts database connections, or enters an infinite loop, the container remains in the Up state even though it cannot serve requests.
The HEALTHCHECK instruction tells Docker how to test if the service is genuinely healthy.
dockerfile
# Healthcheck running every 30s, failing after 3 retries
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1
--interval: Time between probe runs (default: 30s).--timeout: Max duration before a probe run is marked failed (default: 30s).--start-period: Grace period for container bootstrap before failures count against retries.--retries: Consecutive failures needed to mark container status as(unhealthy).- When unhealthy, Docker Swarm and AWS ECS automatically restart or replace the container.