测试容器健康检查功能
·
1.下载 busybox 镜像
[root@host1 ~]# docker pull busybox
Using default tag: latest
latest: Pulling from library/busybox
Digest: sha256:ab33eacc8251e3807b85bb6dba570e4698c3998eca6f0fc2ccb60575a563ea74
Status: Image is up to date for busybox:latest
docker.io/library/busybox:latest
2.执行以下两条命令
[root@host1 ~]# docker run --rm --name test-health -d --health-cmd 'stat /etc/passwd || exit 1' --health-interval 20s --health-retries 1 busybox sleep 1d
930c090f3cdbb818d19129b6505abfad7443cef2b492a50340be44211d7e01ea
[root@host1 ~]# docker inspect --format '{{.State.Health.Status}}' test-health
healthy
两条命令使用分号分隔。其中,第1条命令基于 busybox 镜像创建名为 test-health 的容器,并为该容器设置健康检查选项,健康检查时间间隔为20s,失败则重试1次;检查命令 stat /etc/passwd Ilexit1的含义是执行 Shell命令,输出/etc/passwd 文件的详细信息,如果找不到该文件则退出当前Shell 并返回状态码1;该容器启动后执行 Shell 命令 sleep Id,休眠1天。
第2条命令用于获取该容器的健康状态信息,结果表明容器启动后的健康状态为healthy。
3.执行以下两条命令
[root@host1 ~]# sleep 20s
[root@host1 ~]# docker inspect --format '{{.State.Health.Status}}' test-health
healthy
4.执行以下命令
[root@host1 ~]# docker exec test-health rm /etc/passwd
[root@host1 ~]# sleep 20s; docker inspect --format '{{.State.Health.Status}}' test-health
unhealthy
5.执行以下命令以 JSON 格式进一步显示容器健康的详细日志信息
[root@host1 ~]# docker inspect --format '{{json .State.Health}}' test-health
{"Status":"unhealthy","FailingStreak":12,"Log":[{"Start":"2025-09-15T15:39:49.699976562+08:00","End":"2025-09-15T15:39:49.743319527+08:00","ExitCode":1,"Output":"stat: can't stat '/etc/passwd': No such file or directory\n"},{"Start":"2025-09-15T15:40:09.747515735+08:00","End":"2025-09-15T15:40:09.784537249+08:00","ExitCode":1,"Output":"stat: can't stat '/etc/passwd': No such file or directory\n"},{"Start":"2025-09-15T15:40:29.789298716+08:00","End":"2025-09-15T15:40:29.832188336+08:00","ExitCode":1,"Output":"stat: can't stat '/etc/passwd': No such file or directory\n"},{"Start":"2025-09-15T15:40:49.837382517+08:00","End":"2025-09-15T15:40:49.877028157+08:00","ExitCode":1,"Output":"stat: can't stat '/etc/passwd': No such file or directory\n"},{"Start":"2025-09-15T15:41:09.877483916+08:00","End":"2025-09-15T15:41:09.922482827+08:00","ExitCode":1,"Output":"stat: can't stat '/etc/passwd': No such file or directory\n"}]}
6.执行以下命令查看当前容器的信息
[root@host1 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
930c090f3cdb busybox "sleep 1d" 16 minutes ago Up 16 minutes (unhealthy) test-health
0dbf7ea2178e registry "/entrypoint.sh /etc…" 5 days ago Up About an hour 0.0.0.0:5000->5000/tcp, [::]:5000->5000/tcp myregistry
7.停止运行该容器,该容器会被自动删除
[root@host1 ~]# docker stop test-health
test-health
更多推荐


所有评论(0)