探针告诉 K8S:应用活着吗?能接流量吗?起来了吗? 结尾附探针配置小案例。
一、三种探针
| 探针 | 问题 | 失败后果 |
|---|---|---|
| livenessProbe | 活着吗? | 重启容器 |
| readinessProbe | 能接流量吗? | 摘出 Service(不重启) |
| startupProbe | 启动了吗? | 启动期间保护(慢启动应用) |
二、探测方式
livenessProbe:
httpGet: # HTTP 探测(最常用)
path: /healthz
port: 8080
initialDelaySeconds: 10
periodSeconds: 10
failureThreshold: 3
---
readinessProbe:
exec: # 命令探测
command: ['cat', '/tmp/healthy']
periodSeconds: 5
---
startupProbe:
tcpSocket: # 端口探测
port: 8080
failureThreshold: 30 # 最多容忍 30×10s 启动时间
periodSeconds: 10
三、参数含义
| 参数 | 含义 |
|---|---|
| initialDelaySeconds | 启动后等多久开始探 |
| periodSeconds | 探测间隔 |
| timeoutSeconds | 单次探测超时 |
| failureThreshold | 连续失败几次判死 |
| successThreshold | 连续成功几次判活(readiness 用) |
四、设计原则
/healthz(liveness):进程级健康(别查依赖!否则依赖挂了全重启)
/ready(readiness): 就绪检查(查 DB/缓存连接、预热完成)
startupProbe: 启动 >30s 的应用(Java/大框架)必配
liveness 别查 DB!(DB 抖动 → 应用全重启 → 雪崩)
readiness 可以查 DB(只是不接流量)
五、常见错误
- initialDelaySeconds 太短 → 没起来就判死 → 重启循环(CrashLoopBackOff);
- liveness 探到依赖 → 依赖挂全重启;
- 探测路径要匿名可访问(别被登录拦截 401);
- failureThreshold 别设太小(网络抖动误杀)。
六、小案例:应用探针配置
apiVersion: apps/v1
kind: Deployment
metadata: { name: myapp }
spec:
replicas: 2
selector: { matchLabels: { app: myapp } }
template:
metadata: { labels: { app: myapp } }
spec:
containers:
- name: myapp
image: myapp:1.0
ports: [{ containerPort: 8080 }]
startupProbe: # 启动保护(最多 60s)
httpGet: { path: /healthz, port: 8080 }
failureThreshold: 30
periodSeconds: 2
livenessProbe: # 存活(不查依赖)
httpGet: { path: /healthz, port: 8080 }
initialDelaySeconds: 0
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
readinessProbe: # 就绪(查 DB/缓存)
httpGet: { path: /ready, port: 8080 }
periodSeconds: 5
successThreshold: 1
failureThreshold: 3
# 验证:模拟不就绪
kubectl exec -it deploy/myapp -- touch /tmp/not-ready
kubectl get pods # Ready 0/1(但不重启)
# 模拟假死
kubectl exec -it deploy/myapp -- kill 1 # liveness 失败 → 自动重启
三探针分工:startup 保启动、liveness 保存活、readiness 保流量 —— 生产应用的标准配置。
七、总结
liveness 重启、readiness 摘流量、startup 保慢启动;/healthz 别查依赖、/ready 可查;参数三配 initialDelay/period/failureThreshold;CrashLoopBackOff 先查探针。