跳到主要内容

健康检查

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

一、认识


基于 HEALTHCHECK 指令来实现 Docker 容器的健康检查

二、语法


2.1 HEALTHCHECK --interval=30s CMD xxx

HEALTHCHECK --interval=30s CMD xxx

  1. HEALTHCHECK --interval=30s CMD curl -f http://localhost:3000 || exit 1

2.2 HEALTHCHECK --interval=30s --timeout=3s CMD xxx

HEALTHCHECK --interval=30s --timeout=3s CMD xxx

  1. HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost:3000 || exit 1

2.3 HEALTHCHECK --interval=30s --timeout=3s --retries=N CMD xxx

HEALTHCHECK --interval=30s --timeout=3s --retries=N CMD xxx

三、测试


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
HEALTHCHECK --interval=5s --timeout=3s --retries=3 CMD curl -f http://localhost:3000 || exit 1
CMD ["node","index.js"]

通过 docker inspect node 或者 docker ps 来查看健康状态