【问题标题】:How to do a health check of a Spring Boot application running in a Docker Container?如何对 Docker 容器中运行的 Spring Boot 应用程序进行健康检查?
【发布时间】:2019-12-22 05:30:06
【问题描述】:

我在 Docker 容器中运行 Spring Boot 应用程序,使用 Docker 文件在容器中启动应用程序。如何检查容器内 Spring Boot 应用程序的健康状况?

如果容器停止或应用程序没有运行,我需要根据健康检查自动重启容器或应用程序。这样,我可以确保 Spring Boot 应用程序始终启动并运行。

【问题讨论】:

  • Spring Boot Actuator 可能是个不错的选择。
  • @LHCHIN 使用 spring Boot Actuator 只能检查运行状况。如果应用程序处于停止状态,我也需要退回应用程序。那么什么是最好的解决方案。并且应用程序在 docker 容器中运行

标签: spring-boot docker docker-compose dockerfile health-check


【解决方案1】:

有很多方法可以独立监控 Spring Boot 应用程序,您可以使用 Spring Boot 执行器。您可以在与应用服务器端口不同的端口上公开“管理健康端口”(如果您使用的是 rest api)。

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

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

您可以使用 docker healthcheck 来检查您的应用程序的健康状况:

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

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

https://docs.docker.com/engine/reference/run/#restart-policies---restart

【讨论】:

    【解决方案2】:

    如果你想使用 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
    

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

    【讨论】:

    • 你好,我试过你的答案,但我总是有状态starting,在所有尝试之后我的服务失败了,因为我从来没有达到healthy。你能告诉我有什么问题吗?我复制你的健康检查只是改变端口。
    • 感谢您的努力,我找到了解决方案。 curl 没有安装,因为我使用了太轻量级的 docker 镜像
    • curl 通常不会安装在许多镜像中,并且也被提及为与 docker-compose 的 healthcheck 组件一起使用的反模式。
    • @AndrewTFinnell 谢谢。搜索了一下,没有找到很多说不使用 curl 的文章。有些,例如这个(blog.sixeyed.com/docker-healthchecks-why-not-to-use-curl-or-iwr)还不错,但不是最近的,但没有建议替代调用 actuator/health 端点以获取 spring-boot 映像那么您建议什么替代方案?
    • @xpmatteo:对于 DB,我宁愿使用 DB 健康检查,例如 Postgres test: ["CMD-SHELL", "pg_isready -U postgres"]
    【解决方案3】:

    这对我有用

     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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 2020-09-19
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 2019-09-08
      相关资源
      最近更新 更多