Liveness 和 Readiness
- Kubernetes有两个探测配置以确定应用程序是饭后准备好接受流量以及应用程序是否仍在运行
- 如果准备就绪探针未返回200,则不会向其发送流量
- 如果活动探针未返回200, 则会重启Pod
- Spring Boot 在Actuator模块内置了一组端点,来提供程序的应用信息,确保应用程序处于活动状态
/actuator/health/readiness 和 /actuator/health/liveness endpoint只有在Spring Boot 2.3.x 版本活以上才有,低于此版本的使用/actuator/health endpoint
配置Readiness探针
apiVersion: apps/v1
kind: Deployment
metadata:
...
name: k8s-demo-app
spec:
...
template:
...
spec:
containers:
...
readinessProbe:
httpGet:
port: 8080
path: /actuator/health/readiness
配置Liveness探针
apiVersion: apps/v1
kind: Deployment
metadata:
...
name: k8s-demo-app
spec:
...
template:
...
spec:
containers:
...
livenessProbe:
httpGet:
port: 8080
path: /actuator/health/liveness
优雅关闭应用程序
由于Kubnernetes以非同步方式关闭应用程序,因此在停止前请求还是有可能路由到即将关闭的应用程序。
为了解决这个问题,我们可以配置应用停止前先睡眠10秒,以便在终止请求请求不会路由到应用程序。
将preStop命令添加到您的deploy.yaml的podspec中
apiVersion: apps/v1
kind: Deployment
metadata:
...
name: k8s-demo-app
spec:
...
template:
...
spec:
containers:
...
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep 10"]
- 当应用程序收到需要关闭的通知时,尽管新的请求将不会发送到此应用程序,但是它也可能还正在处理一些未完成的请求.
- 为了使我们能够在应用程序关闭前完成这些请求的处理,我们可以在应用程序中配置一个"宽限期"
- 在application.properties 文件内添加下面的配置
server.shutdown.grace-period=30s
server.shutdown.grace-period 配置只有在Spring Boot 2.3.x 版本活以上才生效
重新构建容器和使新的k8s描述文件生效
./mvnw clean package
kubectl apply -f ./k8s
- Kubernetes将创建新的Pod,旧的Pod将会停止