Health Check for Docker Container - saviovettoor/DevOps-wiki GitHub Wiki
In Docker, a health check is a command used to determine the health of a running container. When a health check command is specified, it tells Docker how to test the container to see if it's working. With no health check specified, Docker has no way of knowing whether or not the services running within your container are actually up or not.
In Docker, health checks can be specified in the Dockerfile as well as in a compose file. I'll cover both implementations in a later step.
A health check is configured in the Dockerfile using the HEALTHCHECK instruction.
HEALTHCHECK [OPTIONS] CMD command
We'll use curl to ensure that our app is serving traffic on port 80.
FROM node:alpine
LABEL MAINTAINER=savio
HEALTHCHECK --interval=5s --timeout=3s --retries=3 \
CMD curl -f http://localhost:80/ || exit 1
EXPOSE 80
RUN mkdir -p /app
WORKDIR /app
ADD server.js ./
COPY package.json ./
CMD ["npm","start"]
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end('<p><strong>My Sample App</strong>!</p>');
});
server.listen(80);
{
"name": "MyNodejsApp",
"version": "1.0.0",
"description": "Introduction to Kubernetes with Node.js",
"main": "server.js",
"scripts": {
"script": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Savio Mathew",
"license": "MIT"
}
docker build -t docker-healthcheck-app:v1 .
NOTE: Make sure running the command from where Dockerfile, server.js, and package.json are located.
docker run --rm --name docker-healthcheck-app -p 80:80 docker-healthcheck-app:v1
docker inspect --format='{{json .State.Health}}' docker-healthcheck-app
after the health check has run the status will change from "Status":"starting" to "Status":"healthy".