Docker Health Checks
Docker Health Checks allow you to monitor the health of your containers and ensure they are running correctly. This guide covers key concepts, steps to create and manage Docker health checks, examples, and best practices for using Docker health checks with Express.js applications.
Key Concepts of Docker Health Checks
- Health Check: A command or script that runs inside a container to determine if the application is running correctly.
- HEALTHCHECK Instruction: A Dockerfile instruction that defines how to test if a container is healthy.
- Health Status: The status of the container based on the health check, which can be "healthy," "unhealthy," or "starting."
Setting Up the Project
Initialize a new Express.js project and create a Dockerfile:
// Initialize a new project
// npm init -y
// Install Express
// npm install express
// Create the project structure
// mkdir src
// touch src/index.js Dockerfile .dockerignore .gitignore
// .gitignore
node_modules
.env
// .dockerignore
node_modules
npm-debug.log
Creating an Express Application
Create a simple Express application:
Example: index.js
// src/index.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, Docker Health Checks!');
});
app.get('/health', (req, res) => {
res.send('Healthy');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Creating a Dockerfile with a Health Check
Create a Dockerfile to containerize your Express application and add a health check:
Example: Dockerfile
// Dockerfile
FROM node:14
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
COPY package*.json ./
RUN npm install
# Bundle app source
COPY . .
# Make port 3000 available to the world outside this container
EXPOSE 3000
# Add health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl --fail http://localhost:3000/health || exit 1
# Run app when the container launches
CMD ["node", "src/index.js"]
Building and Running the Docker Container
Build and run the Docker container for your Express application:
// Build the Docker image
docker build -t my-express-app .
// Run the Docker container
docker run -p 3000:3000 my-express-app
// Open http://localhost:3000 in your browser to see the application running
Checking Container Health Status
Use Docker commands to check the health status of your container:
// List containers and their health status
docker ps
// Inspect a specific container to see detailed health status
docker inspect --format='{{json .State.Health}}'
Using Docker Compose with Health Checks
Set up Docker Compose to manage multi-container applications with health checks:
Example: docker-compose.yml
// docker-compose.yml
version: '3.8'
services:
web:
image: my-express-app
ports:
- "3000:3000"
healthcheck:
test: ["CMD", "curl", "--fail", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 5s
// Run Docker Compose
docker-compose up --build
// Open http://localhost:3000 in your browser to see the application running
Best Practices for Using Docker Health Checks
- Use Health Checks for Critical Services: Ensure that critical services have health checks to monitor their status.
- Set Appropriate Intervals: Set health check intervals that balance the need for timely detection with system performance.
- Use Simple and Reliable Commands: Use simple and reliable commands for health checks to avoid false negatives.
- Monitor Health Status: Use monitoring tools to track the health status of your containers and take action when they become unhealthy.
- Automate Recovery: Configure your orchestration tool to automatically restart or replace unhealthy containers.
Testing Docker Health Check Integration
Test your Docker health check setup to ensure it works correctly:
Example: Testing with Mocha and Chai
// Install Mocha and Chai
// npm install --save-dev mocha chai
// test/app.test.js
const chai = require('chai');
const expect = chai.expect;
const axios = require('axios');
describe('Express App', () => {
it('should return healthy status', async () => {
const response = await axios.get('http://localhost:3000/health');
expect(response.data).to.equal('Healthy');
});
});
// Add test script to package.json
// "scripts": {
// "test": "mocha"
// }
// Run tests
// docker run -p 3000:3000 my-express-app
// npm test
Key Points
- Health Check: A command or script that runs inside a container to determine if the application is running correctly.
- HEALTHCHECK Instruction: A Dockerfile instruction that defines how to test if a container is healthy.
- Health Status: The status of the container based on the health check, which can be "healthy," "unhealthy," or "starting."
- Follow best practices for using Docker health checks, such as using health checks for critical services, setting appropriate intervals, using simple and reliable commands, monitoring health status, and automating recovery.
Conclusion
Docker health checks allow you to monitor the health of your containers and ensure they are running correctly. By understanding and implementing the key concepts, steps, examples, and best practices covered in this guide, you can effectively use Docker health checks to manage your Express.js applications. Happy coding!