Hi All, this document deals with how to add health check for Docker containers.
Since most of the application uses docker for running the applications, It is always required to monitor the health of the docker containers to see the application inside is running or not.

There are certain cases where docker containers run whereas the application inside the docker container won’t. So using the health check would be able to understand the application is running within the container.

Healthcheck commands try to retrieve Response 200 from the application service using curl command, if the response is 200 then it’s container is healthy, otherwise unhealthy.

Here is an example of how I have enabled health check for a sample nodejs application. You can get the source code for the application from this Link.

Enabling docker health check has to be done in Dockerfile using the keyword “HEALTHCHECK”.

Here is the sample dockerfile command where health check is enabled.

 

FROM ubuntu:latest
RUN apt-get update && apt-get install -y nodejs && apt-get -y install npm && apt-get install -y curl
COPY main.js /tmp/main.js
CMD node /tmp/main.js
EXPOSE 8081
HEALTHCHECK CMD curl --fail http://localhost:8081/ || exit 1

Build the container with health check enabled

docker build -t nodejs .

Run the docker container

└──╼ #docker run -d -p 8081:8081 nodejs:app
9b01e1e09f962c1d646e4eb7a6d9d5a5990466e2ed701f8616ced96d51fd0f17
┌─[root@parrot]─[/home/prabhin]
└──╼ #docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9b01e1e09f96 nodejs:app "/bin/sh -c 'node /t…" 5 seconds ago Up 2 seconds (health: starting) 0.0.0.0:8081->8081/tcp unruffled_yonath

Now you can see in the status health: starting, once the docker container is Up and running the status gets changed to healthy.

 

└──╼ #docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9b01e1e09f96 nodejs:app "/bin/sh -c 'node /t…" About a minute ago Up About a minute (healthy) 0.0.0.0:8081->8081/tcp unruffled_yonath

Implementing health check will more useful when using docker swarm, so containers can be restarted whenever the manager identifies container is unhealthy.
It is always better to create a module in the application to check health check status.

© 2019, Techrunnr. All rights reserved.

#1
#2
#3
Questions Answered
Articles Written
Overall Points
Categories: devopsdocker

Prabhin Prabharkaran

He is Technical professional. He is a person who loves to share tricks and tips on the Internet. He Posts what he does!!

Leave a Reply

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.