--health-cmd: 检查的命令
--health-interval:两次健康检查的间隔
--health-timeout:健康检查命令运行超时时间,超过代表失败
--health-retries:当连续失败指定次数后,则将容器状态视为 unhealthy
--health-start-period: 容器启动的初始化时间,此时健康检查失效不会计入次数
docker run 的方式运行一个新容器:
docker run --name web3 -d -p 8080:80 --privileged -v /home/sugarppig/nginx/web1/:/var/www/html/ \
--health-cmd="curl --silent --fail http://localhost:80/ || exit 1" --health-interval=3s --health-retries=3 \
--health-timeout=5s \
centos:jdk
我们接下来可以尝试把 web3 容器里面的网站关掉。可以看到变成了 unhealthy。
docker inspect web3 可以看到结果
只看 Health 部分:
docker inspect --format='{{json .State.Health}}' web3
使用 docker compose 的方式运行容器,修改 docker-compose.yaml
# 加入
healthcheck:
test: ["CMD", "curl","-s","-f", "http://localhost:80"]
interval: 5s
timeout: 5s
retries: 3
services:
nginx:
container_name: mynginx
image: "centos:nginx"
healthcheck:
test: ["CMD","curl","-s","-f","http://localhost:80"]
interval: 5s
timeout: 5s
retries: 3
ports:
- "9090:80"
privileged: true
volumes:
- "/home/sugarppig/nginx/conf/nginx.conf:/etc/nginx/nginx.conf"
networks:
mynginx-net:
ipv4_address: ${nginx_addr}
web1:
container_name: web1
image: "centos:jdk"
healthcheck:
test: ["CMD","curl","-s","-f","http://localhost:80"]
interval: 5s
timeout: 5s
retries: 3
ports:
- "8080:80"
privileged: true
volumes:
- "/home/sugarppig/nginx/web1/:/var/www/html/"
networks:
mynginx-net:
ipv4_address: ${web1_addr}
web2:
container_name: web2
image: "centos:jdk"
healthcheck:
test: ["CMD","curl","-s","-f","http://localhost:80"]
interval: 5s
timeout: 5s
retries: 3
ports:
- "8081:80"
privileged: true
volumes:
- "/home/sugarppig/nginx/web2/:/var/www/html/"
networks:
mynginx-net:
ipv4_address: ${web2_addr}
networks:
mynginx-net:
driver: bridge
ipam:
config:
- subnet: 192.156.0.0/16
version: "3"
重新构建容器
docker-compose up -d
进入 web1 容器,并停掉网站,重新查看,已经检查到 web1 unhealthy