跳到主要内容

健康检查

2024年07月18日
柏拉文
越努力,越幸运

一、认识


基于 healthCheck 指令来检查健康状态

二、语法


services:
serviceA:
image: imageA:Tag
serviceB:
image: imageB:Tag
depends_on:
- serviceA // serviceA 启动成功后,启动B , 不管 serviceA 服务是否有效
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000"]
interval: 30s
timeout: 3s
retries: 3
serviceC:
image: imageC:Tag,
depends_on:
serviceB:
condition: service_healthy // 当 serviceB 服务处于 healthy 时, 才可以启动 serviceC

三、测试


3.1 Node 健康检查

index.js

const http = require("http");
const PORT = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end(`Hello from Node.js`);
});

server.listen(PORT, () => {
console.log(`Server running at port ${PORT}`);
});

Dockerfile

FROM node:latest
WORKDIR /app
COPY . /app
EXPOSE 3000
CMD ["node","index.js"]

docker-compose.yml

services:
node1:
build:
context: .
dockerfile: Dockerfile
container_name: node1
ports:
- 3000:3000
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000"]
interval: 30s
timeout: 3s
retries: 3
networks:
- node1
node2:
image: node:latest
container_name: node2
depends_on:
node1:
condition: service_healthy
networks:
- node1

networks:
node1:
driver: bridge