Open In App

What is Docker Health Check ?

Docker Healthcheck instruction facilitates maintaining optimal docker container performance. It watchfully makes your container well-maintained by letting them know the status of the container. This article demonstrates the health check usage and its significance through a practical go-through using a Nginx container in the docker environment.

What Is HEALTHCHECK Instruction In Docker?

The HEATHCHECK instruction is a feature in Docker that determines the state of a Docker Container. It determines whether the Container is running in a normal state or not. It performs health checks at regular intervals. The initial state is starting and after a successful checkup, the state becomes healthy. If the test remains unsuccessful, it turns into an unhealthy state

Docker HealthCheck

Docker Healthcheck is an instruction that comes with 2 forms of commands. Those syntaxes are specified below. Mainly this instruction is used as a command to know the status of the container and verify whether it is still working or not. The status of the container’s health becomes healthy to unhealthy after certain number of failures.



Syntax:

HEALTHCHECK   [ OPTIONS ]   CMD  command 

( or )

Syntax:

HEALTHCHCK NONE

Health Check Configurations

Options

Functionality

–interval

It determines the interval between 2 health check-ups. The default interval is the 30s.

–timeout

If the HEALTHCHECK command exceeds the specified duration, it is categorized as a failure. The default duration is the 30s.

–retries

If it reaches the specified number of retries, the state is considered to be unhealthy. The default number of retries is 3.

–start-period

It heps in defining the delay period before the first retry attempt. By default it will be started immediately.

–start-interval

It helps in determining the interval between the first and second retry. By default the interval will be 4 seconds.

Docker Healthcheck Examples

Docker Health check instructions are defined inside the Dockerfile or in Docker-Compose files. For bettering here we defining a sample healthcheck in a Dockerfile, for a docker container that running a web server.

 FROM nginx:latest

# Define a healthcheck command
HEALTHCHECK --interval=30s --timeout=10s --retries=3 CMD curl -f http://localhost/ || exit 1

How to Write a Custom Health Check Scripts

For writing a custom health check, you can go for shell scripting in that you can write the code for performing necessary checks and returns. If status is healthy then exit value is 0 or if status is unhealthy then the exit value is non-zero. Here is an example using a shell script.

#!/bin/bash

# Check if a service is running
if pgrep "myservice" > /dev/null
then
exit 0 # Service is running, healthcheck passes
else
exit 1 # Service is not running, healthcheck fails
fi

Writing a Custom Health Check in Nodejs

// healthcheck.js
const http = require('http');

const server = http.createServer((req, res) => {
res.writeHead(200);
res.end('Healthcheck OK');
});

server.listen(3000, () => {
console.log('Healthcheck server running on port 3000');
});
node healthcheck.js
FROM node:latest

COPY healthcheck.js /app/healthcheck.js

# Define a custom healthcheck command
HEALTHCHECK --interval=30s --timeout=10s --retries=3 CMD ["node", "/app/healthcheck.js"]

After running a container with this Dockerfile, the node js application keeps on running for every 30 seconds with a timeout of 10 seconds and retrives of 3.

Common Usages For Docker Health Checks

Let’s start with discussing the docker health check instruction usage in the docker environment before diving into the practical exposure, The following are a few wider uses of the health check instruction.

Evaluating The Health Of The Container

Periodical Healthcheck

Customizable Parameters

Enhanced Troubleshooting

Application Crashes

Health checks facilitates with monitoring the application’s status within the container. If in anycase, the application get crashed or it becomes unresponsive then the health check will detects the state and alerts of the docker daemon.

Depedency Failures

Mostly applications will depend on the external things like databases or APIs. Health checks help with verifying the availability and responsiveness of those dependencies. If any dependency looks in failed state or in unreachable then the health check mark it as unhealthy and facilitates Docker in triggering the right measures such as relocating or restarting the container.

Resource Limitations

Health checks facilitating in monitoring the utilization of the resources usage within the containers such as CPU and memory utilization. Health check reports this unhealthy state to the Docker and Docker will takes measures in redistributing the resources or restarting the containers on different hosts.

Misconfigurations

Invalid, Incorrect configurations of applications leads to instability and failure of the applications. It verifies the essential configuration parameters such as network connectivity settings or environment variables. Health check look over the application status if any misconfiguration are detected then it is prompted to Docker to stop those containers and provides the feedback for troubleshooting.

Now let’s see with practical examples of how to use the HEALTHCHECK Instruction in your Dockerfile. We will create an Nginx Container and determine it states.

How To Use And Run Docker’s Health Check Command: A Step-By-Step Guide

The following are the step-by-step guidelines for the implementation of the health check in docker using Nginx Image:

Step 1: Create A Dockerfile

FROM nginx:latest
HEALTHCHECK --interval=35s --timeout=4s CMD curl -f https://localhost/ || exit 1
EXPOSE 80

Step 2: Build The Docker Image

sudo docker build -t healthcheck-demo .

Step 3: Run the Container

sudo docker run --name=healthcheck-demo -d
--health-cmd='stat /etc/nginx/nginx.conf
|| exit 1' healthcheck-demo

/* This line must be without the breaks, it's done for viewing purpose*/

Step 4: Determine the state of the Container

sudo docker inspect --format=' ' healthcheck-demo

Docker HealthCheck Commands

docker inspect --format='{{json .State.ExitCode}}' <container_name>

docker inspect --format='{{json .State.ExitCode}}' mycontainer

Docker HealthCheck Docker-Compose

services:
myservice:
image: myimage
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 30s

Docker HealthCheck curl

HEALTHCHECK --interval=30s --timeout=10s --retries=3 CMD curl -f http://localhost || exit 1

Docker health Check Logs

docker inspect --format='{{json .State.Health}}' <container_name>
docker inspect --format='{{json .State.Health}}' mycontainer

Docker Health Check Ports

docker ps
docker port <container_name>

Docker Health Check Scripts

HEALTHCHECK --interval=30s --timeout=10s --retries=3 CMD ["./healthcheck.sh"]

Docker Health Check Status

docker inspect --format='{{json .State.Health.Status}}' <container_name>

Conclusion

To conclude, in this article we discussed what is HEALTHCHECK instructions, what are its uses, the various options you can use along with it. We used the nginx container to demonstrate the same with practical examples. It’s usage is crucial for monitoring and maintaining the health of containerized applications. Implementation of health checks with Docker applications will be an effective practice for ensuring reliability and stability to the containerized applications.

Docker HealthCheck Instruction – FAQ’s

What Is The Healthcheck In Docker?

It refers to the HEALTHCHECK instruction, a feature allowing the definition of periodic checks to knows the status of container’s health.

What is Health Check In Dockerfile or Docker Compose?

Healthcheck is an instructions that check status of the application whether it is reachable or unreachable, properly working or being instable. It is defined as command in Dockerfile or DockerCompose to check the health of the containerized applications ensuring its reliability and availability.

What is the cURL command for Docker Health check?

The commonly used curl command for Docker health checks is curl -f <URL>`. It checks if the specified URL is reachable ( successful ) or it coming with non-zero exit status code known as failure state.

How Do I Disable Healthcheck In Docker?

You can disable the docker healthcheck, on onmiting the healthcheck instruction in the Dockerfile or by using `–no-healthcheck` during the `docker run` command.

How To Check The Container Status In Docker?

On using docker inspect command particularly with the –format=’ ‘ you can retrieve the detailed information, including the container’s health status.

Does Kubernetes Use Docker Healthcheck Instruction?

Yes, Kubernetes use the docker healthcheck as part of its container orchestration facilitating health status of containers.

How Does The Docker Compose Healthcheck Work?

In Docker compose the healthchecks are defined in the service’s configuration of the compose file specifying the test commands and options.


Article Tags :