为你的docker容器增加一个健康检查机制

2019-04-22 分类:云计算 阅读(2849) 评论(0)

在分布式系统中,经常需要利用健康检查机制来检查服务的可用性,防止其他服务调用时出现异常。自 1.12 版本之后,Docker 引入了原生的健康检查实现。

如何给Docke配置原生健康检查能力,在写dockerfile的时候,通过HEALTHCHECK指令就可以了

 

dockerfile如下:

FROM nginx:1.13

ADD test.sh /opt/test.sh

HEALTHCHECK --interval=10s --timeout=3s --retries=3 CMD /bin/bash /opt/test.sh

 

脚本如下:

vi /opt/test.sh

#!/bin/bash

cat /var/run/nginx.pid

if [ $? == 0 ];then

echo 0

exit 0

else

echo 1

exit 1

fi

 

指令分析:

HEALTHCHECK --interval=10s --timeout=3s --retries=3 CMD /bin/bash /opt/test.sh

--interval 代表间隔,每隔10秒执行一次脚本

--timeout 脚本执行超时时间

--retries 脚本失败次数,3次失败,即30秒之后,标记容器为unhealthy

 

服务正常启动案例:

[root@k8s-node-1 opt]# docker run -d 10.0.0.11:5000/nginx:1.13.1

be97b9980431d326d9b745ec3f605c227caa085d50529926d27562ae1e339e39

[root@k8s-node-1 opt]# docker ps -a -l

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

be97b9980431 10.0.0.11:5000/nginx:1.13.1 "nginx -g 'daemon off" 4 seconds ago Up 3 seconds (health: starting) 80/tcp pensive_chandrasekhar

[root@k8s-node-1 opt]# docker ps -a -l

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

be97b9980431 10.0.0.11:5000/nginx:1.13.1 "nginx -g 'daemon off" 11 seconds ago Up 10 seconds (healthy) 80/tcp pensive_chandrasekhar

 

服务不正常启动案例:

[root@k8s-node-1 opt]# docker run -d 10.0.0.11:5000/nginx:1.13.1 tail -f /etc/hosts

b3b0b5a280930e40753da6174f22fd014510715c8757ad43928c2833a40a516d

[root@k8s-node-1 opt]# docker ps -a -l

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

b3b0b5a28093 10.0.0.11:5000/nginx:1.13.1 "tail -f /etc/hosts" 38 seconds ago Up 38 seconds (unhealthy) 80/tcp furious_poincare

 

容器死掉自动重启案例:

[root@k8s-node-1 opt]# docker run --restart=always -d 10.0.0.11:5000/nginx:1.13.1 sleep 40

fd1017e1ce4f063e4110689ae476f2307ab0d6ce23286f64b102a949b58f657a

[root@k8s-node-1 ~]# docker ps -a -l

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

fd1017e1ce4f 10.0.0.11:5000/nginx:1.13.1 "sleep 40" 33 seconds ago Up 32 seconds (unhealthy) 80/tcp tiny_mccarthy

[root@k8s-node-1 ~]# docker ps -a -l

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

fd1017e1ce4f 10.0.0.11:5000/nginx:1.13.1 "sleep 40" 56 seconds ago Up 14 seconds (health: starting) 80/tcp tiny_mccarthy

 

评论已关闭

登录

忘记密码 ?

切换登录

注册