HPA

官方文档:https://kubernetes.io/zh-cn/docs/tasks/run-application/horizontal-pod-autoscale/

1.简介

HPA​(Horizontal Pod Autoscaler,Pod水平自动伸缩),根据平均 CPU 利用率、平均内存利用率或你指定的任何其他自定义指标自动调整 Deployment​ 、ReplicaSet​ 或 StatefulSet​ 或其他类似资源,实现部署的自动扩展和缩减,让部署的规模接近于实际服务的负载。HPA不适用于无法缩放的对象,例如DaemonSet。

实际生产中,一般使用这四类指标:

  1. Resource metrics——CPU核 和 内存利用率指标。
  2. Pod metrics——例如网络利用率和流量。
  3. Object metrics——特定对象的指标,比如Ingress, 可以按每秒使用请求数来扩展容器。
  4. Custom metrics——自定义监控,比如通过定义服务响应时间,当响应时间达到一定指标时自动扩容。

先决条件

  1. 必须安装 metrics-server(在metrics-server中添加--kubelet-insecure-tls参数跳过证书校验)
  2. 必须定义 Request参数
  3. 开启 API Aggregator参数

配置Aggregator参数:

cat /etc/kubernetes/manifests/kube-apiserver.yaml
# 添加这行
--enable-aggregator-routing=true

v1

apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler 
metadata:
  name: hpa_name
spec:
  maxReplicas: 5
  minReplicas: 2 
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: myapp
  targetCPUUtilizationPercentage: 60

v2

apiVersion: autoscaling/v2beta1
kind: HorizontalPodAutoscaler
metadata:
  name: hpa_name
spec :
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: myapp
  minReplicas: 3
  maxReplicas: 10 
  metrics:
  - type: Resource
    resource:
      name: cpu
      targetAverageUtilization: 80
    resource:
      name: memory
      targetAverageValue: 800Mi

2.案例

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: hpa-nginx
spec:
  maxReplicas: 10 # 最大扩容到10个节点(pod)
  minReplicas: 1 # 最小扩容1个节点(pod)
  metrics:
  - resource:
      name: cpu
      target:
        averageUtilization: 50 # CPU 平局资源使用率达到50%就开始扩容,低于50%就是缩容
        # 设置内存
        # AverageValue:50
        type: Utilization
    type: Resource
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: hpa-nginx
---
apiVersion: v1
kind: Service
metadata:
  name: hpa-test
spec:
  type: NodePort
  ports:
    - name: "http"
      port: 80
      targetPort: 80
      nodePort: 30080
  selector:
    service: hpa-test
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hpa-test
spec:
  replicas: 1
  selector:
    matchLabels:
      service: hpa-test
  template:
    metadata:
      labels:
        service: hpa-test
    spec:
      containers:
        - name: hpa-test
          image: nginx:latest
          resources:
            requests:
              cpu: 100m
              memory: 100Mi
            limits:
              cpu: 200m
              memory: 200Mi

主要参数解释如下:

  • scaleTargetRef:目标作用对象,可以是Deployment、ReplicationController或ReplicaSet。
  • minReplicas和maxReplicas:Pod副本数量的最小值和最大值,系统将在这个范围内进行自动扩缩容操作,并维持每个Pod的内存使用率为50%,这个值就是上面设置的阈值averageUtilization。
  • metrics:目标指标值。在metrics中通过参数type定义指标的类型;通过参数target定义相应的指标目标值,系统将在指标数据达到目标值时(考虑容忍度的区间,见前面算法部分的说明)触发扩缩容操作。
  • 对于CPU使用率,在target参数中设置averageUtilization定义目标平均CPU使用率。
  • 对于内存资源,在target参数中设置AverageValue定义目标平均内存使用值。

压测:

ab -n 10000 -c 800 http://192.168.1.1:30080/