本文目是体验Docker容器的健康检查功能,以体验为主不涉及开发,与开发相关的内容会在后面的文章细说。
考虑这样的情况:docker环境中,springboot应用的容器还在,但已无法提供服务(例如数据或文件被破坏,线程池等资源被耗尽等各种异常),此时需要一种方式快速得知这种状态。此时容器健康检查(即HEALTHCHECK)就派上用场了,只要容器按照Docker的规则提供自身状态信息,就可以将容器健康信息以多种方式告知外界;
docker官方文档说明,HEALTHCHECK功能从1.12版本开始提供,这里对docker社区版的版本号做个简介:
docker run --rm --name=healthcheck -p 8080:8080 --health-cmd="curl --silent --fail localhost:8080/getstate || exit 1" --health-interval=15s --health-retries=10 --health-timeout=5s bolingcavalry/dockerhealthcheck:0.0.1-SNAPSHOT
(base) zhaoqindeMacBook-Pro:~ zhaoqin$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d86c11321cef bolingcavalry/dockerhealthcheck:0.0.1-SNAPSHOT "JAVA -Xms1g -Xmx1g …" 13 seconds ago Up 12 seconds (health: starting) 8080/tcp healthcheck (base) zhaoqindeMacBook-Pro:~ zhaoqin$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d86c11321cef bolingcavalry/dockerhealthcheck:0.0.1-SNAPSHOT "java -Xms1g -Xmx1g …" 17 seconds ago Up 16 seconds (healthy) 8080/tcp healthcheck
2019-10-20 03:05:02.350 INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 2019-10-20 03:05:02.364 INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 14 ms 2019-10-20 03:05:02.384 INFO 1 --- [nio-8080-exec-1] c.b.d.DockerhealthcheckApplication : step probe return success 2019-10-20 03:05:17.584 INFO 1 --- [nio-8080-exec-2] c.b.d.DockerhealthcheckApplication : step probe return success 2019-10-20 03:05:32.748 INFO 1 --- [nio-8080-exec-3] c.b.d.DockerhealthcheckApplication : step probe return success
可见容器自启动后,该接口每隔15秒就会调用一次;
2019-10-20 03:38:51.428 INFO 1 --- [nio-8080-exec-3] c.b.d.DockerhealthcheckApplication : step probe return success 2019-10-20 03:39:06.592 INFO 1 --- [nio-8080-exec-9] c.b.d.DockerhealthcheckApplication : step probe return fail 2019-10-20 03:39:21.757 INFO 1 --- [io-8080-exec-10] c.b.d.DockerhealthcheckApplication : step probe return fail 2019-10-20 03:39:36.912 INFO 1 --- [nio-8080-exec-3] c.b.d.DockerhealthcheckApplication : step probe return fail
(base) zhaoqindeMacBook-Pro:~ zhaoqin$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 070e56cc99f2 bolingcavalry/dockerhealthcheck:0.0.1-SNAPSHOT "java -Xms1g -Xmx1g …" 18 minutes ago Up 18 minutes (unhealthy) 0.0.0.0:8080->8080/tcp healthcheck
(base) zhaoqindeMacBook-Pro:~ zhaoqin$ docker events --filter event=health_status 2019-10-20T12:19:18.349588676+08:00 container health_status: unhealthy 2d538f8752ae1e94ce23f34b7fb71c8f2ea3a075df82943ffdbe62c49ad4d6c8 (image=bolingcavalry/dockerhealthcheck:0.0.1-SNAPSHOT, name=healthcheck) 2019-10-20T12:20:19.030857534+08:00 container health_status: healthy 2d538f8752ae1e94ce23f34b7fb71c8f2ea3a075df82943ffdbe62c49ad4d6c8 (image=bolingcavalry/dockerhealthcheck:0.0.1-SNAPSHOT, name=healthcheck)
至此,docker容器健康体验完毕,我们已经对此功能有了基本认识,接下来实战中,我们会尝试让自己的应用容器支持健康检查功能;