将Spring Boot Actuator作为Kubernetes的探针使用
我想做的事情
希望将Spring Boot应用程序容器化并在Kubernetes上运行时,希望在Kubernetes的探针中指定Spring Boot Actuator。
确认的环境如下所示。
-
- Spring Boot 2.4.10および2.5.4
-
- AdoptOpenJDK 16.0.1
-
- macOS Big Sur 11.5.2
- Kubernetes 1.18.0 on Minikube 1.23.0
首先,”Probe”是什么意思?
Probe是为了监视Kubernetes中Pod内容器而设计的功能。
探针有以下3种类型。
下面是具体的三种Probe执行方法。
对于像使用Spring Boot创建的Web应用程序这样的情况,通常会选择使用选项1。
Spring Boot Actuator的Probe功能
Spring Boot Actuator 在2.3版本中添加了Probe功能(请参考发布说明)。
具体来说,以下的Actuator端点已被添加。
没有为Startup Probe准备相应的端点。在Spring Boot参考文档中有如下内容。
在这里并不一定需要”startupProbe”,因为在所有启动任务完成之前,”readinessProbe”会失败。
总的来说,您的意思是”可以使用Readiness Probe替代吗?”对吗?
执行器使用方法
(1) 增加依存性
在pom.xml文件中添加spring-boot-starter-actuator。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
...
</dependencies>
(2) application.properties文件的设置
要启用Probe的Actuator端点,有两种方法可供选择(只需选择其中一种方法即可)。
-
- 在application.properties文件中设置management.endpoint.health.probes.enabled=true
- 判断是否在Kubernetes上运行(检查是否有环境变量*_SERVICE_HOST和*_SERVICE_PORT)
在Kubernetes上运行时,即使有management.endpoint.health.probes.enabled=true,也没有害处,因此基本上可以使用第一种方法。
只需要公开health终端点就可以了。
综上所述,如果按照以下的方式编写application.properties即可。
management.endpoint.health.probes.enabled=true
management.endpoints.web.exposure.include=health
management.health.livenessstate.enabled 和 management.health.readinessstate.enabled 也有这个设置,但我不太理解它们的意思…稍后会进行再次调查。
对Kubernetes清单的描述
在”路径”字段中指定了Actuator的路径。
apiVersion: apps/v1
kind: Deployment
metadata:
name: hoge
labels:
app: hoge
spec:
replicas: 1
selector:
matchLabels:
app: hoge
template:
metadata:
labels:
app: hoge
spec:
containers:
- name: hoge
image: hoge:0.0.1
ports:
- containerPort: 8080
...
livenessProbe:
initialDelaySeconds: 10
httpGet:
port: 8080
path: /actuator/health/liveness
periodSeconds: 5
timeoutSeconds: 1
successThreshold: 1
failureThreshold: 1
readinessProbe:
initialDelaySeconds: 10
httpGet:
port: 8080
path: /actuator/health/readiness
periodSeconds: 5
timeoutSeconds: 1
successThreshold: 1
failureThreshold: 2
...
请参考以下资料。
- Spring Boot Reference 2.9. Kubernetes Probes