Kubernetes HPA(Horizontal Pod Autoscaler)根据CPU利用率、内存使用或自定义指标自动调整Pod副本数量,是保障服务稳定性和资源利用率的核心机制。配合ResourceQuota和LimitRange实现命名空间级别的资源配额管理,能够有效防止单个应用耗尽集群资源。本文从HPA配置、自定义指标集成、资源配额三个维度展开实战。
HPA自动伸缩原理与指标采集
HPA通过Metrics Server采集集群资源指标,周期性(默认15秒)查询当前Pod的资源利用率,与目标值比较后决定扩缩容操作。扩容操作即时执行,缩容操作有默认300秒的冷却时间,防止频繁波动。
HPA工作流程:
1. Metrics Server从各节点的kubelet收集CPU和内存指标
2. HPA控制器查询目标Deployment的当前指标值
3. 根据公式计算期望副本数:期望副本数 = ceil(当前副本数 * (当前指标 / 目标指标))
4. 调用Deployment的Scale子资源更新副本数
安装Metrics Server:
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
# 验证安装
kubectl top nodes
kubectl top pods -A
HPA配置实战:基于CPU和内存的伸缩策略
基础HPA配置,基于CPU利用率自动伸缩:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-api-hpa
namespace: production
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-api
minReplicas: 3
maxReplicas: 50
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 30
selectPolicy: Max
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 50
periodSeconds: 60
- type: Pods
value: 4
periodSeconds: 60
selectPolicy: Min
关键参数说明:
– minReplicas/maxReplicas:最小和最大副本数边界。
– averageUtilization: 70:CPU平均利用率超过70%触发扩容。
– scaleUp.stabilizationWindowSeconds: 0:扩容无冷却,立即响应。
– scaleDown配置了两种策略取最小值:每分钟最多缩减50%或4个Pod,避免雪崩。
Deployment必须配置resources.requests才能被HPA监控:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-api
spec:
replicas: 3
template:
spec:
containers:
- name: api
image: registry.example.com/web-api:v2.1
resources:
requests:
cpu: 250m
memory: 256Mi
limits:
cpu: 500m
memory: 512Mi
自定义指标伸缩:Prometheus Adapter集成
当CPU和内存指标不足以反映业务负载时,可通过Prometheus Adapter接入自定义指标,如QPS、消息队列深度、活跃连接数等。
部署Prometheus Adapter配置文件:
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>>)'
该规则将Prometheus中的http_requests_total指标转换为每秒请求数,HPA可基于此指标伸缩。
基于自定义QPS指标的HPA:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api-qps-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-api
minReplicas: 3
maxReplicas: 100
metrics:
- type: Pods
pods:
metric:
name: http_requests_per_second
target:
type: AverageValue
averageValue: "1000"
当每个Pod平均QPS超过1000时触发扩容。type: Pods表示该指标以Pod为单位采集,不需要Resource类型的指标。
多指标组合策略:HPA会在所有指标中取计算出的最大期望副本数,确保任何一个指标超限都能触发扩容。
ResourceQuota与LimitRange资源配额管理
ResourceQuota限制命名空间的总资源消耗,LimitRange设置单个Pod或Container的资源上下限。两者配合实现多层资源控制。
ResourceQuota配置:
apiVersion: v1
kind: ResourceQuota
metadata:
name: production-quota
namespace: production
spec:
hard:
requests.cpu: "100"
requests.memory: 200Gi
limits.cpu: "200"
limits.memory: 400Gi
persistentvolumeclaims: "20"
services.loadbalancers: "5"
pods: "200"
configmaps: "50"
secrets: "50"
该配置限制production命名空间最多使用100个CPU核心、200Gi内存请求,200个CPU核心、400Gi内存上限,最多200个Pod。
LimitRange配置:
apiVersion: v1
kind: LimitRange
metadata:
name: container-limits
namespace: production
spec:
limits:
- type: Container
max:
cpu: "4"
memory: 8Gi
min:
cpu: 100m
memory: 128Mi
default:
cpu: 500m
memory: 512Mi
defaultRequest:
cpu: 250m
memory: 256Mi
- type: PersistentVolumeClaim
max:
storage: 100Gi
min:
storage: 1Gi
关键配置项:
– max/min:单个容器资源上下限,超过max或低于min的Pod将被拒绝创建。
– default:未指定limits时的默认上限。
– defaultRequest:未指定requests时的默认请求值。
验证配额使用情况:
# 查看命名空间配额使用
kubectl describe resourcequota production-quota -n production
# 查看LimitRange
kubectl describe limitrange container-limits -n production
VPA垂直伸缩与节点自动扩缩
HPA解决水平伸缩,VPA(Vertical Pod Autoscaler)解决垂直伸缩——自动调整Pod的CPU和内存requests/limits。
VPA安装与配置:
# 安装VPA
kubectl apply -f https://github.com/kubernetes/autoscaler/releases/latest/download/vpa-v1-upgrade.yaml
# 创建VPA资源
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: api-vpa
namespace: production
spec:
targetRef:
apiVersion: "apps/v1"
kind: Deployment
name: web-api
updatePolicy:
updateMode: Auto
resourcePolicy:
containerPolicies:
- containerName: api
minAllowed:
cpu: 100m
memory: 128Mi
maxAllowed:
cpu: "2"
memory: 4Gi
controlledResources: ["cpu", "memory"]
VPA有三种模式:Auto(自动调整并重启Pod)、Initial(仅在创建时设置requests)、Off(仅推荐不执行)。生产环境建议先用Off模式观察推荐值,确认合理后切换为Auto。
集群节点自动扩缩(Cluster Autoscaler):
# AWS EKS集群自动扩缩配置
apiVersion: apps/v1
kind: Deployment
metadata:
name: cluster-autoscaler
namespace: kube-system
spec:
template:
spec:
containers:
- name: cluster-autoscaler
image: registry.k8s.io/autoscaling/cluster-autoscaler:v1.30.0
command:
- ./cluster-autoscaler
- --cloud-provider=aws
- --scale-down-unneeded-time=10m
- --scale-down-delay-after-add=10m
- --max-node-provision-time=15m
- --balance-similar-node-groups
- --expander=priority
Cluster Autoscaler监控Pending状态的Pod,当因资源不足导致Pod无法调度时自动新增节点。空闲节点超过scale-down-unneeded-time后自动回收。HPA和Cluster Autoscaler协同工作:HPA负责应用层水平扩缩,Cluster Autoscaler负责基础设施层节点扩缩。
原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/kubernetes-rong-qi-bian-pai-shi-zhan-hpa-zi-dong-shen-suo/