梗概
kubernetes探针是用于检查容器健康状况的机制,确保只有健康的容器才能接收流量,并在容器异常时自动重启或隔离。
核心概念
- Liveness Probe(存活探针):判断容器是否存活,失败时kubelet会重启容器
- Readiness Probe(就绪探针):判断容器是否准备好接收流量,失败时从Service端点中移除
- Startup Probe(启动探针):检查容器应用是否已启动,为慢启动容器提供额外时间
详细说明
探针类型详解
1. Liveness Probe(存活探针)
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3作用机制:
- 定期检查容器内应用是否正常运行
- 检测到应用死锁、无响应等状态时触发重启
- 与Pod的重启策略配合工作
典型场景:
- Java应用出现内存泄漏导致无响应
- 应用进入死循环状态
- 数据库连接池耗尽
2. Readiness Probe(就绪探针)
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5作用机制:
典型场景:
- 应用启动过程中需要加载配置
- 依赖的外部服务暂时不可用
- 应用正在执行数据库迁移
3. Startup Probe(启动探针)
startupProbe:
httpGet:
path: /startup
port: 8080
failureThreshold: 30
periodSeconds: 10作用机制:
- 为慢启动应用提供足够的启动时间
- 启动期间禁用其他探针
- 适用于启动时间较长的遗留应用
探针检查方式
HTTP GET
httpGet:
path: /health
port: 8080
httpHeaders:
- name: Custom-Header
value: AwesomeTCP Socket
tcpSocket:
port: 8080执行命令
exec:
command:
- cat
- /tmp/healthy配置参数
| 参数 | 说明 | 默认值 |
|---|---|---|
initialDelaySeconds | 容器启动后等待多久开始探测 | 0 |
periodSeconds | 探测频率 | 10 |
timeoutSeconds | 探测超时时间 | 1 |
successThreshold | 连续成功次数阈值 | 1 |
failureThreshold | 连续失败次数阈值 | 3 |
最佳实践
1. 探针端点设计
- 轻量级检查:避免复杂的业务逻辑检查
- 快速响应:确保探针端点能快速返回结果
- 区分检查类型:为不同探针设计不同的检查逻辑
2. 参数调优
# 生产环境推荐配置
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 60 # 给应用足够启动时间
periodSeconds: 30 # 适中的检查频率
timeoutSeconds: 10 # 合理的超时时间
failureThreshold: 3 # 避免误杀
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 33. 与Spring Boot集成
# application.yml
management:
health:
probes:
enabled: true
livenessState:
enabled: true
readinessState:
enabled: true
endpoint:
health:
show-details: always
probes:
enabled: true故障排查
常见问题
- 探针频繁失败:检查应用启动时间、网络延迟
- 误重启:调整
failureThreshold和timeoutSeconds - 流量中断:检查readiness探针逻辑是否过于严格
调试命令
# 查看Pod事件
kubectl describe pod <pod-name>
# 查看探针日志
kubectl logs <pod-name> -c <container-name>
# 手动测试探针端点
kubectl exec -it <pod-name> -- curl localhost:8080/health探针机制是kubernetes实现应用高可用的关键组件,与控制器、Service等组件协同工作,确保集群中只有健康的容器实例对外提供服务。