健康检查
2024年07月18日
一、认识
二、Dockerfile
Dockerfile
可以通过 HEALTHCHECK
来检查 Docker
的运行状态
2.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
HEALTHCHECK --interval=5s --timeout=3s --retries=3 CMD curl -f http://localhost:3000 || exit 1
CMD ["node","index.js"]
通过 docker inspect node
或者 docker ps
来查看健康状态
三、DockerCompose
Docker Compose
通过 healthcheck
来进行健康检查
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