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

18

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

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


Spring Boot Actuator可能是一个不错的选择。 - LHCHIN
通过使用Spring Boot Actuator,您可以仅检查应用程序的健康状况。如果应用程序处于停止状态,我需要将其弹起。那么这个问题的最佳解决方案是什么?并且该应用程序正在Docker容器中运行。 - Sandeep muthyapu
4个回答

26

如果您想将 Spring Bootactuator/health 用作 Docker 健康检查,则必须在您的 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)。


5
谢谢你的努力,我找到了解决方案。由于我使用的是轻量级的 Docker 镜像,因此没有安装 curl。 - Denis Stephanov
6
许多镜像中通常未安装 curl,而且在使用 docker-composehealthcheck 组件时也被称为反模式。 - Andrew T Finnell
2
@AndrewTFinnell 谢谢。我搜索了一下,没有找到很多文章说不要使用curl。例如这篇文章(https://blog.sixeyed.com/docker-healthchecks-why-not-to-use-curl-or-iwr/)虽然不错但已经有些过时了,而且没有提供调用spring-boot镜像的`actuator/health`端点的替代方法。那么你有什么替代方法建议呢? - LE GALL Benoît
2
@xpmatteo:在数据库的情况下,我更愿意使用数据库健康检查,例如使用Postgres test: ["CMD-SHELL", "pg_isready -U postgres"] - LE GALL Benoît
1
默认情况下,不健康的状态返回503,而健康(和未知)状态返回200。使用grep查找“UP”的cURL本身可能已足够:curl --fail --silent localhost:8081/actuator/health - M. Justin
显示剩余5条评论

6

这对我有效

 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

请告诉我,在使用com.bmuschko.docker-spring-boot-application插件的Gradle SpringBoot应用程序中,我们如何使用相同的命令。该插件将使用Gradle任务提供的配置创建Dockerfile。 - ABHISHEK KUMAR

0

我的服务器在索引上进行重定向,因此我使用重定向来进行健康检查,如下所示:

healthcheck:
  test: curl -Is localhost:8080 | head -n 1 | grep 302 || exit 1

-2

有很多方法可以监控Spring Boot应用程序的基础知识,独立使用Spring Boot Actuator。如果您正在使用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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接