存活探针、就绪探针、启动探针的配置与最佳实践
在Kubernetes中,健康检查是确保应用可靠性的关键机制。通过健康检查,Kubernetes可以:
Pod → 探针检查 → 状态评估 → 相应操作(重启/流量控制)
作用:检测容器是否存活,若探测失败,Kubernetes会重启容器。
使用场景:应用可能出现死锁、崩溃等情况,需要自动恢复。
作用:检测容器是否准备就绪,若探测失败,Kubernetes会将Pod从服务端点移除。
使用场景:应用启动需要时间初始化(如加载配置、数据库连接)。
作用:检测容器是否完成启动,若探测成功,其他探针开始工作。
使用场景:应用启动时间较长,避免因启动时间过长被误判为失败。
Kubernetes支持三种探针实现方式:
apiVersion: v1
kind: Pod
metadata:
name: health-check-demo
spec:
containers:
- name: nginx
image: nginx:1.21
ports:
- containerPort: 80
livenessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 30 # 容器启动后延迟30秒开始探测
periodSeconds: 10 # 每10秒探测一次
timeoutSeconds: 5 # 探测超时时间
successThreshold: 1 # 成功阈值
failureThreshold: 3 # 失败阈值
readinessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 5
periodSeconds: 10
startupProbe:
httpGet:
path: /
port: 80
failureThreshold: 30 # 允许最多30次失败
periodSeconds: 10 # 给应用300秒启动时间
apiVersion: v1
kind: Pod
metadata:
name: tcp-health-check
spec:
containers:
- name: redis
image: redis:6.2
ports:
- containerPort: 6379
livenessProbe:
tcpSocket:
port: 6379
initialDelaySeconds: 20
periodSeconds: 10
readinessProbe:
tcpSocket:
port: 6379
initialDelaySeconds: 5
periodSeconds: 10
apiVersion: v1
kind: Pod
metadata:
name: exec-health-check
spec:
containers:
- name: app
image: busybox
command: ["/bin/sh", "-c", "echo 'running' > /tmp/healthy; sleep 30; rm /tmp/healthy; sleep 600"]
livenessProbe:
exec:
command:
- cat
- /tmp/healthy
initialDelaySeconds: 5
periodSeconds: 5
readinessProbe:
exec:
command:
- cat
- /tmp/healthy
initialDelaySeconds: 5
periodSeconds: 5
# 查看Pod状态和事件
kubectl get pods
kubectl describe pod <pod-name>
# 查看容器的健康检查状态
kubectl get pod <pod-name> -o jsonpath='{.status.containerStatuses[*].state}'
# 模拟健康检查失败
# 进入容器删除健康检查文件
kubectl exec -it <pod-name> -- rm /tmp/healthy
# 观察Pod状态变化
kubectl get pods -w
解决方案:使用启动探针,设置较长的failureThreshold和periodSeconds
解决方案:适当增加periodSeconds,减少探测频率
解决方案:检查应用日志,分析就绪探针失败原因,可能是配置错误或依赖服务不可用
健康检查是Kubernetes确保应用可靠性的关键机制,通过合理配置三种探针类型,可以:
在实际应用中,需要根据应用的特性和需求,选择合适的探针类型和配置参数,以达到最佳的健康检查效果。