What is Docker Health Check?



Docker has changed the way we develop, package, and run applications by providing a means of packaging applications and their dependencies into lightweight containers. However, it is just as important to ensure that your containers are healthy and running as it is to get them deployed. This is where Docker Health Checks come in.

Why Do We Need Docker Health Checks?

When you are running your applications in Docker containers, just checking whether the container is ?running' is not enough. A container can be started, but may be stuck in an infinite loop, waiting for a connection, or experiencing runtime exceptions. By default, the docker ps command in Docker does not show whether the application within the container is functioning properly or not, it only tells you whether the container is ?Up' or ?Exited'.
This problem is solved by health checks, which allow Docker to check whether the normally running containerized application is actually in a healthy state. If a health check fails, the Docker can signal the container as ?unhealthy', alert, restart the container or notify an orchestration tool like Kubernetes to take an action.

Prerequisites

To follow along, make sure you have:
Docker installed: Download and install Docker from the official website of Docker.
Basic knowledge of Docker: Understanding of images, containers and Dockerfiles.
A simple application: We will use a simple web server for the demonstration.

How to Implement Docker Health Checks

Docker has introduced the HEALTHCHECK instruction that can be used in a Dockerfile or in a docker-compose.yml file. There are three main approaches:

1. Using a Shell Command

This is the simplest way to perform a health check by executing a command within the container.
Example: Adding a Health Check to a Node.js App
First create a server.js file with an Express server:
const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.send('Server is running!');
});

app.listen(3000, () => console.log('Server started on port 3000'));

Then, create a Dockerfile:

FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["node", "server.js"]

# Add Health Check
HEALTHCHECK --interval=10s --timeout=3s --retries=3 \
CMD curl -f http://localhost:3000 || exit 1

Explanation:
--interval=10s: The health check is going to be performed 10s after the last check.
--timeout=3s: The check should not take more than 3 seconds to finish.
--retries=3: If 3 attempts fail, the container is considered unhealthy.
The curl command used is: CMD curl -f http://localhost:3000 || exit 1 If curl fails, then the container is unhealthy.

2. Using a Custom Script

For more sophisticated health checks, the script offers more flexibility.

Example: Health Check Script

Create a healthcheck.sh file:

#!/bin/sh
if curl -f http://localhost:3000; then
exit 0 # Healthy
else
exit 1 # Unhealthy
fi

Change the Dockerfile to use this script:

COPY  healthcheck.sh /healthcheck.sh
RUN chmod +x /healthcheck.sh
HEALTHCHECK --interval=10s --timeout=3s --retries=3 CMD /healthcheck.sh

 3. Using Docker Compose

When working with many containers, it is easier to define health checks in docker-compose.yml than in the Dockerfile.
Example: Health Check in Docker Compose

version: '3.8'
services:
web:
image: python-docker-health
build: .
ports:
- "5000:5000"
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:5000/health"]
interval: 30s
timeout: 10s
retries: 3

Explanation:
test: The command to run, curl -f ensures that an HTTP request is successful.
interval, timeout, retries: These work identical to how they did in the Dockerfile example.

Checking Container Health Status

After building and running the container, to check the health of the container, use:
docker inspect --format='{{json.State.Health}}' container_name

It returns a JSON object with health status, logs and failure count. Alternatively, list running containers with health status:

docker ps

It will show a (healthy) or (unhealthy) status in the container name column.

Why Are Health Checks Important?

Health checks are crucial in:

Automated Recovery: Automatic restart of unhealthy containers.

Improved Reliability: Load balancers do not send traffic to unhealthy containers.

Better Monitoring: Learn about container health for debugging and alerting.

Best Practices for Docker Health Checks

Keep It Lightweight: Health checks should not be too compute intensive and should not consume a lot of system resources.
Use Application-Specific Checks: The check should be related to the crucial functions of your application.
Test Thoroughly: Validate health checks before putting them into production.
Use Multiple Retries: Do not fail a container as unhealthy because of problems that are likely to be transient.

Conclusion

Docker Health Checks are an important feature that is used in order to ensure that your containerized applications are operating at an optimum level. Health checks can be achieved using shell commands, custom scripts or Docker Compose to make sure that only healthy containers are accepting requests.

When you use Docker Health Checks in your workflows, you can develop stronger applications, failover processing, and increase your visibility.
Updated on: 2025-03-19T12:06:17+05:30

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements