Docker应用健康探针:
# Dockerfile构建时加入健康检查探针
示例如下:
FROM node:11.15.0-alpine
MAINTAINER wollens
WORKDIR /code
RUN apk update && apk upgrade && \
apk add --no-cache bash git curl
HEALTHCHECK --interval=2m --timeout=10s --start-period=5s --retries=3 CMD curl -f http://127.0.0.1:8012/ || exit 1
ADD src /code/src
COPY package.json ./
COPY tsconfig.json ./
RUN npm install
EXPOSE 8012
RUN npm run compile
CMD npm run start
# docker run命令行执行健康探针
示例如下:
$ docker run -d \
--name=myweb \
--health-cmd="curl -fs http://localhost/ || exit 1" \
--health-interval=5s \
--health-retries=12 \
--health-timeout=2s \
nginx:1.23
Docker-compose部署应用健康探针:
# docker-compose.yml中添加参数
示例如下:
version: "3"
services:
server:
build: .
image: test:0.0.7
volumes:
- .:/code
- /code/node_modules
ports:
- "8012:8012"
environment:
MYSQL_HOST: mysqldb
links:
- mysqldb
healthcheck:
test: ["CMD", "curl", "-f", "http://127.0.0.1:8012"/, "||", "exit", "1"]
#test: ["CMD-SHELL", "mysql --host=127.0.0.1 --user=root --password=$$MYSQL_ROOT_PASSWORD --silent --execute \"SELECT 1;\" || exit 0"]
interval: 2m
timeout: 10s
retries: 3
mysqldb:
image: mysql:5.6
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: xxx
MYSQL_DATABASE: test
#mariadb的docker-compose.yml
version: '3.3'
services:
mariadb:
container_name: mariadb
image: mariadb:10.4.26
restart: always
hostname: mariadb
volumes:
- /docker/mariadb/data:/var/lib/mysql
- /docker/mariadb/conf.d/server.cnf:/etc/mysql/conf.d/server.cnf
- /docker/mariadb/conf.d/my.cnf:/etc/mysql/my.cnf
- /etc/localtime:/etc/localtime
environment:
- MYSQL_ROOT_PASSWORD=admin
- TZ=Asia/Shanghai
ports:
- "3306:3306"
healthcheck:
test: "mysqladmin -uroot -p'admin' ping"
deploy:
resources:
limits:
cpus: '2'
memory: 2G
#启动
docker-compose --compatibility up -d
K8S方式部署应用健康探针:
LivenessProbe探针
用于判断容器是否存活,即Pod是否为running状态,如果LivenessProbe探针探测到容器不健康,则kubelet将kill掉容器,并根据容器的重启策略是否重启,如果一个容器不包含LivenessProbe探针,则Kubelet认为容器的LivenessProbe探针的返回值永远成功。
ReadinessProbe探针:
用于判断容器是否启动完成,即容器的Ready是否为True,可以接收请求,如果ReadinessProbe探测失败,则容器的Ready将为False,控制器将此Pod的Endpoint从对应的service的Endpoint列表中移除,从此不再将任何请求调度此Pod上,直到下次探测成功。
每类探针都支持三种探测方法:
exec:通过执行命令来检查服务是否正常,针对复杂检测或无HTTP接口的服务,命令返回值为0则表示容器健康。
httpGet:通过发送http请求检查服务是否正常,返回200-399状态码则表明容器健康。
tcpSocket:通过容器的IP和Port执行TCP检查,如果能够建立TCP连接,则表明容器健康。
示例如下:
cat test.yaml
apiVersion: v1
kind: pod
metadata:
labels:
test: liveness
name: liveness-exec
spec:
containers:
- name: liveness
image: gcr.io/google_containers/busybox
args:
- /bin/sh
- -c
- echo ok > /tmp/health; sleep 10; rm -rf /tmp/health; sleep 600
livenessProbe:
exec:
command:
- cat
- /tmp/health
initialDelaySeconds: 15
timeoutSeconds: 1
参考资料:
k8s-pod健康检查_探针 - 风儿飘 - 博客园
docker-compose healthcheck 检查tcp端口是否通 – 小菜菜的博客
Docker容器的健康检查 - 对我家键盘温柔点 - 博客园
Docker 容器的 health 健康状态检查
docker和docker-compose中加入healthcheck_流浮生的博客-CSDN博客_docker-compose healthcheck