Add a health check to a Docker container running a simple Node.js application.
Question
Add a health check to a Docker container running a simple Node.js application. The health check should verify that the application is running and accessible.
Sample Healthcheck API in node.js,
app.js
// app.js
const express = require('express');
const app = express();
// A simple route to return the status of the application
app.get('/health', (req, res) => {
res.status(200).send('OK');
});
// Example main route
app.get('/', (req, res) => {
res.send('Hello, Docker!');
});
// Start the server on port 3000
const port = 3000;
app.listen(port, () => {
console.log(`App is running on http://localhost:${port}`);
});Solution
Step 1: Create a Dockerfile
Create a Dockefile to containerize the node app. It also should include a health check command. https://docs.docker.com/reference/dockerfile/#healthcheck
HEALTHCHECK: The health check is added at the end of the Dockerfile. It checks the/healthendpoint of your application every 30 seconds.--interval=30s: Check the health every 30 seconds.--timeout=5s: If the health check takes longer than 5 seconds, it’s considered a failure.--start-period=5s: Wait 5 seconds before starting the first health check.--retries=3: If the health check fails 3 consecutive times, the container is considered unhealthy.
Step 2: Build and Run the Docker Image
First, build the Docker image,

Then, run the container,
Step 3: Verify the Health Check
To check the status of the container’s health, run
In the output, you should see a STATUS column that will change from starting to healthy once the health check passes.

Last updated