在 Kubernetes 中,健康检查(Probe) 是保障服务稳定运行的核心能力之一。
但在实际使用中,Readiness 和 Liveness 经常被混用、误用,轻则导致流量抖动,重则引发 Pod 频繁重启、雪崩效应。
本文将从设计目的、工作机制、差异、示例、最佳实践、进阶玩法全方位讲解,并结合 Spring Boot 案例给出完整配置。
在没有健康检查之前,K8S 只能知道:
Pod 是否存在、容器是否在运行
但这远远不够:
Readiness 与 Liveness 就是为了解决这些问题而设计的。
判断 Pod 是否“就绪”接收流量
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
timeoutSeconds: 2
failureThreshold: 3
@Component
public class ReadinessHealthIndicator implements HealthIndicator {
@Override
public Health health() {
if (dbAvailable() && cacheAvailable()) {
return Health.up().build();
}
return Health.down().withDetail("reason", "dependency unavailable").build();
}
}
判断容器是否处于“不可恢复的异常状态”
⚠️ 不适合:
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 60
periodSeconds: 10
timeoutSeconds: 2
failureThreshold: 3
@Component
public class LivenessHealthIndicator implements HealthIndicator {
@Override
public Health health() {
if (threadPoolAlive() && mainLoopAlive()) {
return Health.up().build();
}
return Health.down().build();
}
}
| 维度 | Readiness | Liveness |
|---|---|---|
| 关注点 | 能否接流量 | 是否需要重启 |
| 失败后果 | 从 Service 摘除 | 容器重启 |
| 是否影响 Pod 生命周期 | 否 | 是 |
| 适合依赖异常 | ✅ 是 | ❌ 否 |
| 适合进程死锁 | ❌ 否 | ✅ 是 |
一句话总结:Readiness 控制“流量”,Liveness 控制“生死”
在滚动升级或缩容时,如果 Pod 立即被删除,可能导致请求被中断。 结合 Readiness + preStop 可以实现 优雅下线:
示例配置:
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 10"]
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
sleep 10 表示给 Pod 10 秒时间处理现有请求Spring Boot 2.x 提供了 Liveness / Readiness 指标分离:
management:
endpoints:
web:
exposure:
include: health
health:
livenessstate:
enabled: true
readinessstate:
enabled: true
/actuator/health/liveness → 只关注进程/actuator/health/readiness → 关注依赖服务(DB、Redis、MQ 等)| 参数 | 建议值 | 说明 |
|---|---|---|
| initialDelaySeconds | Liveness: 60~120sReadiness: 10~30s | 应用启动慢,避免误判 |
| periodSeconds | 5~15s | 探针检查间隔 |
| timeoutSeconds | 1~5s | 请求超时 |
| failureThreshold | 3~5 | 连续失败次数才判定失败 |
原则:
用好 Readiness 和 Liveness,是 Kubernetes 可靠性和服务稳定性的基石。