使用Kubernetes的主要好处之一是它能够管理和维护在集群中运行的容器,且能保证几乎没有停机时间。
而这个功能主要是k8s通过探测程序的就绪状态(readiness)和活动状态(liveness)来实现对程序的健康进行管理的。
在本文中,我们将使用Spring Boot Actuator为我们提供的端点来为K8s提供活动状态(liveness)和就绪状态(readiness)的探测,我们将探讨如何使用k8s内置的活动状态和就绪状态探测来管理和控制应用程序的运行状况。Spring Boot自2.3版本开始提供了此功能。
什么是就绪状态探测(Readiness Probe)
在 Kubernetes 中,“就绪状态”探测是一种机制,用于确定容器是否准备好接受流量并处理请求。 “就绪状态”探测用于确保一个容器已经准备好可以开始接收请求,通常用于在容器启动后执行一些额外的操作(例如预热缓存、加载配置文件等)。
在 Kubernetes 中,如果所有容器都在正常运行并通过了其各自的“就绪状态”探测,Pod 会被标记为“就绪”。如果一个容器的就绪状态探测失败,它将被标记为“未就绪”,并且 Kubernetes将不会将流量路由到该容器。这可以确保Pod只有在所有容器都准备好处理流量时才能被视为“就绪”,从而提高应用程序的可用性和稳定性。
什么是活动状态探测(Liveness Probe)
在 Kubernetes 中,“活动状态”探测是一种用于检测应用程序是否正在运行的机制。它通过定时向容器发送HTTP请求或执行命令来检查容器内的应用程序是否仍然处于运行状态。如果应用程序没有响应或者返回了错误的响应,那么Kubernetes将视为该容器已经死亡,并且将自动重启容器,以确保应用程序始终处于运行状态。
如何让Spring Boot提供就绪状态和活动状态
Spring Boot Actuator为我们提供的端点来为K8s提供活动状态(liveness)和就绪状态(readiness)的探测。
Spring Boot和K8s
我们只需要在我们的程序里添加依赖:
Gradle:
implementation 'org.springframework.boot:spring-boot-starter-actuator'
Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
在application.properties 里开启两个状态:
management.endpoint.health.probes.enabled=true
当使用这个配置后,Spring Boot将会暴露“就绪状态”和“使用状态”两个端点:
/actuator/health/liveness
/actuator/health/readiness
本地启动可以访问:
http://ip:port/actuator/health/liveness
http://ip:port/actuator/health/readiness
liveness
readiness
修改k8s的deployment.yml :
apiVersion: apps/v1
kind: Deployment
metadata:
name: spring-boot-actuator-endpoint
spec:
selector:
matchLabels:
app: spring-boot-actuator-endpoint
replicas: 1
template:
metadata:
labels:
app: spring-boot-actuator-endpoint
spec:
containers:
- name: spring-boot-actuator-endpoint
image: spring-boot-actuator-endpoint:0.0.2
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
livenessProbe:
httpGet:
path: /actuator/health/liveness # 1
port: 8080
initialDelaySeconds: 20
periodSeconds: 3
readinessProbe:
httpGet:
path: /actuator/health/readiness # 2
port: 8080
initialDelaySeconds: 20 # 3
periodSeconds: 3 # 4
- 将Spring Boot Actuator的liveness端口填写在此处。
- 将Spring Boot Actuator的readiness端口填写在此处。
- initialDelaySeconds 在执行第一次探测前应该等待 20秒。
- periodSeconds 每隔3秒执行一次探测。
当使用新的deployment.yml部署或者更新项目时,k8s就会使用这两个端点对程序的就绪状态和活动状态进行检测。