Kubernetes2026-04-15·7 分钟
Kubernetes 探针与弹性伸缩
介绍 readiness/liveness 探针、水平弹性伸缩和资源限制的实践方法。
Kubernetes 探针与弹性伸缩
1. Liveness Probe
Liveness 探针用于判断容器是否存活,如果失败,Kubernetes 会重启容器。
yaml
livenessProbe:
httpGet:
path: /health
port: 80
initialDelaySeconds: 30
periodSeconds: 102. Readiness Probe
Readiness 探针用于判断容器是否准备好接收请求,未准备好则不会纳入 Service 负载池。
yaml
readinessProbe:
httpGet:
path: /ready
port: 80
initialDelaySeconds: 5
periodSeconds: 53. 资源请求与限制
yaml
resources:
requests:
cpu: '250m'
memory: '256Mi'
limits:
cpu: '500m'
memory: '512Mi'requests用于调度。limits用于运行时限流。
4. 水平 Pod 自动伸缩
yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: myapp-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: myapp
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 605. 弹性伸缩建议
- 不要把最小实例数设为 0,避免冷启动延迟。
- 根据实际负载和启动时间设置合理指标。
- 同时配置
readinessProbe,确保新 Pod 只有在健康后才接收流量。
6. 常见问题
- 探针配置过严可能导致容器频繁重启。
- 未设置资源请求时,Pod 可能被调度到不合适的 Node。
- HPA 需要 Metrics Server 或外部指标支持。
Kubernetes探针弹性伸缩