在Kubernetes集群中进行应用部署性能调优是每个SRE和DevOps工程师必须掌握的核心技能。本文将分享一些实用的调优经验和可复现的操作步骤。
资源请求与限制设置
首先,合理设置Pod的资源请求(request)和限制(limit)至关重要。以一个典型的Web应用为例,可以通过以下YAML配置进行优化:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
spec:
replicas: 3
selector:
matchLabels:
app: web-app
template:
metadata:
labels:
app: web-app
spec:
containers:
- name: app-container
image: nginx:1.21
resources:
requests:
memory: "128Mi"
cpu: "100m"
limits:
memory: "256Mi"
cpu: "200m"
水平Pod自动伸缩(HPA)配置
通过HPA可以实现根据CPU使用率自动扩缩容:
kubectl autoscale deployment web-app --cpu-percent=70 --min=3 --max=10
垂直Pod自动伸缩(VPA)实践
对于资源需求不稳定的场景,建议启用VPA:
apiVersion: vpa.apps.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: web-app-vpa
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: web-app
updatePolicy:
updateMode: Auto
节点亲和性优化
通过节点亲和性避免Pod被调度到不合适的节点上:
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: node-type
operator: In
values: ["production"]
性能监控与分析
使用Prometheus监控关键指标,重点关注Pod的内存和CPU使用率:
rate(container_cpu_usage_seconds_total{container="app-container"}[5m])
通过以上配置和监控,可以显著提升K8s应用部署的稳定性和性能表现。

讨论