如何对在 docker 容器中运行的 Spring Boot 应用程序进行健康检查

San*_*apu 6 docker spring-boot dockerfile docker-compose

如何检查在 docker 容器内运行的 spring boot 应用程序的健康状况,以及容器是否停止或应用程序未运行我需要根据健康检查状态自动重新启动容器或应用程序,以便 spring boot 应用程序将启动并运行每个人都可以帮助我我正在使用docker文件在容器中启动spring boot

LE *_*oît 13

如果你想使用spring boot actuator/health作为docker healthcheck,你必须像这样在你的docker-compose 文件中添加它:

    healthcheck:
      test: "curl --fail --silent localhost:8081/actuator/health | grep UP || exit 1"
      interval: 20s
      timeout: 5s
      retries: 5
      start_period: 40s
Run Code Online (Sandbox Code Playgroud)

编辑: 这里的端口是management.server.port. 如果您没有指定它,它应该是server.port value(默认为8080)

  • 许多镜像中通常没有安装“curl”,并且也被认为是与 docker-compose 的“healthcheck”组件一起使用的反模式。 (6认同)
  • 感谢您的努力,我找到了解决方案。没有安装curl,因为我使用了太轻量级的docker镜像 (3认同)
  • @AndrewTFinnell 谢谢。我搜索了一下,没有找到很多说不使用curl的文章。有些,例如这个(https://blog.sixeyed.com/docker-healthchecks-why-not-to-use-curl-or-iwr/)还不错但不是最近的,但没有提出替代方案调用 spring-boot 映像的“actuator/health”端点 那么您建议作为替代方案吗? (2认同)
  • @xpmatteo:就数据库而言,我宁愿使用数据库运行状况检查,例如使用 Postgres `test: ["CMD-SHELL", "pg_isready -U postgres"]` (2认同)

小智 7

这对我有用

 healthcheck:
  test: curl -m 5 --silent --fail --request GET http://localhost:8080/actuator/health | jq --exit-status -n 'inputs | if has("status") then .status=="UP" else false end' > /dev/null || exit 1
  interval: 10s
  timeout: 2s
  retries: 10
Run Code Online (Sandbox Code Playgroud)


Rob*_*lly -2

独立监控 Spring Boot 应用程序的基础知识有很多,您可以使用 Spring Boot 执行器。您可以在与应用程序服务器端口不同的端口上公开“管理运行状况端口”(如果您使用的是 REST API)。

https://docs.spring.io/spring-boot/docs/current/reference/html/development-ready-endpoints.html

只需在 pom.xml 中包含 spring 执行器依赖项,并在 applicaiton.properties/.yml 中配置它,这将公开上面链接中列出的端点。

您可以使用 docker healthcheck 检查应用程序的运行状况:

https://docs.docker.com/engine/reference/builder/#healthcheck

您可以设置重启策略以确保容器在崩溃时重新启动:

https://docs.docker.com/engine/reference/run/#restart-policies---重新启动