我正在 Docker 容器中运行 Spring Boot 应用程序,使用 Docker 文件启动容器中的应用程序。如何检查容器内 Spring Boot 应用程序的运行状况?
如果容器停止或应用程序未运行,我需要根据健康检查自动重新启动容器或应用程序。这样,我可以确保 Spring Boot 应用程序始终启动并运行。
如果您想使用 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)
这对我有用
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
我的服务器对索引进行重定向,因此我使用重定向进行健康检查,如下所示:
healthcheck:
test: curl -Is localhost:8080 | head -n 1 | grep 302 || exit 1
对于那些使用旧 LTS eclipse-temurin:17-jre-alpine 或当前 LTS eclipse-temurin:21-jre-alpine 的用户,
wget
包含在默认图像中,因此开箱即用 docker compose 的 healthcheck 看起来像:
healthcheck:
test: "wget -T5 -qO- http://localhost:8080/actuator/health | grep UP || exit 1"
interval: 15s
timeout: 5s
retries: 5
start_period: 20s
对于 kubernetes 来说是
spec:
containers:
...
livenessProbe:
httpGet:
path: /actuator/health
port: 8080
initialDelaySeconds: 20
periodSeconds: 15
failureThreshold: 5
timeoutSeconds: 5
当状态代码在 200 到 399 之间时,httpGet healthcheck 探针将认为应用程序运行状况良好。 如果应用程序报告健康状态,/actuator/health API 将在其关闭时响应 200 和 503,从而满足 k8s 健康检查探测。
有很多方法可以使用 Spring Boot Actuator 来进行独立监控 Spring Boot 应用程序的基础知识。您可以在与应用程序服务器端口不同的端口上公开“管理运行状况端口”(如果您使用的是 REST API)。
https://docs.spring.io/spring-boot/docs/current/reference/html/product-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---重新启动