博客作为学习笔记记录,若有理解,表述错误,欢迎指出。
healthcheck是docker1.12版本引入的新功能,用于容器健康状态监测
暂时k8s不支持docker的healthcheck功能,k8s由其之前就提供的liveness和readiness功能来实现healthcheck,docker引入healthcheck功能,估计也是向k8s学习的。
docker 的healthcheck
设置选项:
--interval=DURATION
(default: 30s
),间隔--timeout=DURATION
(default: 30s
), 超时时间--start-period=DURATION
(default: 0s
),初始化时间说明:在此期间的探测失败将不计入最大重试次数。但是,如果健康检查在启动期间成功,则认为容器已启动,所有连续的失败都将计入最大重试次数。
--retries=N
(default: 3
),当连续失败指定次数后,容器状态会变成unhealthy格式:HEALTHCHECK [选项] CMD(分成shell格式和exec格式)。
如果有多个指令,则最后一个生效。
输出: healthcheck命令执行的结果有以下几种:
举个栗子:
用curl来判断web服务是否正常,在dockerfile中定义healthcheck:
FROM nginx
RUN apt-get update && apt-get
install -y curl && rm -rf /var/lib/apt/lists/*
HEALTHCHECK --interval=5s --timeout=3s \
CMD curl -fs http://localhost/ || exit 1
刚运行容器时,容器状态为health:starting
$ docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
03e28eb00bd0 myweb:v1 "nginx -g 'daemon off" 3 seconds ago Up 2 seconds (health: starting) 80/tcp, 443/tcp web
过几秒之后,状态会变成healthy
$ docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
03e28eb00bd0 myweb:v1 "nginx -g 'daemon off" 18 seconds ago Up 16 seconds (healthy) 80/tcp, 443/tcp web
健康指令的输出结果会存储在健康状态里,可以用docker inspect来查看,eg:
$ docker inspect --format '{{json .State.Health}}' web | python -m json.tool
#输出为:
{
"FailingStreak": 0,
"Log": [
{
"End": "2016-11-25T14:35:37.940957051Z",
"ExitCode": 0,
"Output": "\n\n\nWelcome to
nginx! \n\n\n\nWelcome to
nginx!
\nIf you see this page, the nginx web server is
successfully installed and\nworking. Further configuration is
required.
\n\nFor online documentation and support please
refer to\nnginx.org.
\nCommercial
support is available at\nnginx.com.
\n\nThank
you for using nginx.
\n\n\n",
"Start":
"2016-11-25T14:35:37.780192565Z"
}
],
"Status": "healthy"
}
REF:
https://docker_practice.gitee.io/image/dockerfile/healthcheck.html
https://docs.docker.com/engine/reference/builder/