Kubernetes环境下SpringBoot应用程序健康检查

生产环境下,对应用运行的状态需要进行健康检查。本文提供了一种健康检查集成方法。用于检查Kubernetes环境下SpringBoot应用程序运行状态。

一、目标

应用部署到K8S环境下,通过K8S的健康检查探针,对SpringBoot应用进行运行健康监控。

二、实施步骤

2.1 SpringBoot应用程序关键配置

考虑到SpringBoot本身已经提供了一组健康指标器可以去使用,通过引入下述依赖就可以获取观察到程序的运行状态。

2.1.1 集成应用监控依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2.1.2 Actuator中应用就绪和存活探针配置

在SpringBoot版本大于2.3时,可以通过以下配置开启应用探针功能:

management:
  server:
    port: 9000
  health:
    readinessstate:
      enabled: true
    livenessstate:
      enabled: true

2.2 Kubernetes 健康检查配置

2.2.1 就绪检查探针配置

initialDelaySeconds:初始延迟,在检查其运行状况之前,容器启动后需要等待多长时间
httpGet:使用Http请求的方式进行检查,k8s也支持TCP连接和命令行。
periodSeconds:执行探测频率(秒),执行探测的频率(以秒为单位)。默认为10秒。最小值为1
timeoutSeconds:超时时间(秒),等待探针完成多长时间。如果超过时间,则认为探测失败。默认为1秒。最小值为1
successThreshold:健康阈值,探测失败后,连续最小成功探测为成功。默认值为1。最小值为1。存活探针和启动探针内,健康阈值必须为1
failureThreshold:不健康阈值,探针进入失败状态时需要连续探测失败的最小次数

在K8S中配置示例:

# deployment等
...
readinessProbe:
  failureThreshold: 3
  httpGet:
    path: /actuator/health/readiness
    port: 9000
    scheme: HTTP
  initialDelaySeconds: 30
  periodSeconds: 10
  successThreshold: 1
  timeoutSeconds: 3
...

2.2.2 存活检查探针配置

在K8S中配置示例:

# deployment等
...
livenessProbe:
  failureThreshold: 3
  httpGet:
    path: /actuator/health/liveness
    port: 9000
    scheme: HTTP
  initialDelaySeconds: 30
  periodSeconds: 10
  successThreshold: 1
  timeoutSeconds: 1
...

更多

SpringBoot探针返回结果中,status 如果不是UP下的处理?


参考

https://www.baeldung.com/spring-boot-kubernetes-self-healing-apps
https://www.baeldung.com/spring-liveness-readiness-probes