Kubernetes Pod自动伸缩机制概述
Kubernetes提供两种Pod级别的自动伸缩机制:HPA(Horizontal Pod Autoscaler)根据指标水平扩展Pod副本数量,VPA(Vertical Pod Autoscaler)根据历史资源使用情况自动调整Pod的CPU和内存请求值。HPA适用于无状态应用和可水平拆分的工作负载,通过增加副本数应对流量增长;VPA适用于无法水平扩展的有状态应用,通过调整单个Pod的资源配额提升处理能力。
HPA依赖Metrics Server采集集群资源使用数据。Metrics Server通过Kubelet的Summary API聚合各节点的CPU、内存使用指标,以metrics.k8s.io API对外提供。HPA Controller定期查询指标,根据当前指标值与目标值的比值计算期望副本数,调用Deployment Controller执行扩缩容操作。
Metrics Server部署与验证
部署Metrics Server前确认各节点的kubelet配置已开启聚合层认证:
# 安装Metrics Server
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.7.0/components.yaml
# 如果使用自签证书集群,需添加--kubelet-insecure-tls参数
kubectl patch deployment metrics-server -n kube-system --type='json' -p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]'
# 验证Metrics Server运行状态
kubectl get pods -n kube-system | grep metrics-server
kubectl top nodes
kubectl top pods --all-namespaces
kubectl top命令能正确输出节点和Pod的CPU、内存使用量表示Metrics Server工作正常。如果输出为空或报错,检查kubelet的–authorization-mode是否包含Webhook、–authentication-token-webhook是否开启。
HPA基于CPU和内存的自动伸缩配置
为Deployment创建HPA规则,设置目标CPU使用率50%、最小副本2个、最大副本10个:
# 先确保Deployment配置了resources.requests
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-api
spec:
replicas: 2
selector:
matchLabels:
app: web-api
template:
metadata:
labels:
app: web-api
spec:
containers:
- name: web-api
image: registry.yunthe.com/web-api:v2.1
resources:
requests:
cpu: 200m # 200 millicores = 0.2核
memory: 256Mi
limits:
cpu: 500m
memory: 512Mi
ports:
- containerPort: 8080
---
# HPA配置
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-api-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-api
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 70
behavior:
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 50
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 30
- type: Pods
value: 4
periodSeconds: 30
selectPolicy: Max
behavior字段控制扩缩容的速率和平滑度。scaleDown.stabilizationWindowSeconds设置为300秒,表示Pod使用率低于目标值后等待5分钟再执行缩容,避免流量波动导致频繁伸缩。scaleDown策略设置为每分钟最多缩减50%副本数,防止缩容过快击穿服务。scaleUp策略selectPolicy设置为Max,取Percent 100%和Pods 4中较大的扩展速率,快速响应流量突增。
自定义指标HPA与Prometheus Adapter集成
基于CPU和内存的HPA无法覆盖QPS、消息队列深度等业务指标。通过Prometheus Adapter将自定义指标暴露为Kubernetes API,HPA可基于业务指标做扩缩容决策。部署Prometheus Adapter前需要运行Prometheus采集应用指标:
# prometheus-adapter配置文件
apiVersion: v1
kind: ConfigMap
metadata:
name: prometheus-adapter-config
namespace: kube-system
data:
config.yaml: |
rules:
- seriesQuery: 'http_requests_total{namespace!="",pod!=""}'
resources:
overrides:
namespace: {resource: "namespace"}
pod: {resource: "pod"}
name:
matches: "^(.*)_total"
as: "${1}_per_second"
metricsQuery: 'sum(rate(<<.Series>>{<<.LabelMatchers>>}[2m])) by (<<.GroupBy>>)'
- seriesQuery: 'nginx_connections_active{namespace!=""}'
resources:
overrides:
namespace: {resource: "namespace"}
name:
matches: "^(.*)"
metricsQuery: 'avg(<<.Series>>{<<.LabelMatchers>>}) by (<<.GroupBy>>)'
# HPA基于自定义QPS指标
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-api-custom-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-api
minReplicas: 3
maxReplicas: 20
metrics:
- type: Pods
pods:
metric:
name: http_requests_per_second
target:
type: AverageValue
averageValue: 1000 # 每个Pod目标处理1000 QPS
seriesQuery定义Prometheus中的指标查询语句,metricsQuery定义聚合方式。Prometheus Adapter将http_requests_total指标转换为每秒请求率,通过custom.metrics.k8s.io API暴露给HPA Controller。当QPS超过每个Pod 1000时,HPA自动增加副本数。
VPA垂直资源配额管理配置
VPA有三种运行模式:Auto模式自动调整Pod的资源请求并在必要时重启Pod;Initial模式仅在Pod创建时设置资源请求,不修改运行中的Pod;Recommender模式只生成资源建议不执行调整。生产环境推荐使用Initial模式避免Pod重启导致服务中断:
# 安装VPA组件
git clone https://github.com/kubernetes/autoscaler.git
cd autoscaler/vertical-pod-autoscaler
./hack/vpa-up.sh
# 创建VPA配置
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: db-vpa
spec:
targetRef:
apiVersion: "apps/v1"
kind: StatefulSet
name: postgres-db
updatePolicy:
updateMode: "Initial" # 仅在新建Pod时生效
resourcePolicy:
containerPolicies:
- containerName: postgres
minAllowed:
cpu: 100m
memory: 256Mi
maxAllowed:
cpu: 2000m
memory: 4Gi
controlledResources: ["cpu", "memory"]
VPA通过分析过去8天的资源使用历史数据,使用百分位算法计算合理的资源请求值。minAllowed和maxAllowed约束调整范围,防止VPA将资源请求设置得过低导致OOM或过高导致资源浪费。controlledResources指定VPA管理的资源类型,不配置limits字段避免VPA调整资源上限导致Pod被OOM Kill。
HPA和VPA不应同时对同一Deployment的同一资源指标生效。HPA基于CPU使用率扩缩容时,VPA同时修改CPU请求值会导致HPA计算基准变化,产生振荡。正确做法是HPA管理无状态应用的水平伸缩,VPA管理有状态应用(如数据库)的资源配额,两者作用对象分离。
原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/kubernetes-ji-qun-hpa-shui-ping-zi-dong-shen-suo-yu-vpa/