Skip to content

02 - 自动扩缩容

三种 Autoscaler

┌─────────────────────────────────────────────────────┐
│                                                     │
│  HPA (Horizontal Pod Autoscaler)                    │
│  水平扩缩:增减 Pod 副本数                            │
│  ┌──┐ ┌──┐ ┌──┐  →  ┌──┐ ┌──┐ ┌──┐ ┌──┐ ┌──┐     │
│  │Po│ │Po│ │Po│     │Po│ │Po│ │Po│ │Po│ │Po│     │
│  └──┘ └──┘ └──┘     └──┘ └──┘ └──┘ └──┘ └──┘     │
│                                                     │
│  VPA (Vertical Pod Autoscaler)                      │
│  垂直扩缩:调整 Pod 的 CPU/内存                       │
│  ┌──────┐  →  ┌──────────┐                          │
│  │ 256Mi│     │  512Mi   │                          │
│  │ 0.5C │     │  1.0C    │                          │
│  └──────┘     └──────────┘                          │
│                                                     │
│  Cluster Autoscaler                                 │
│  集群扩缩:增减节点数量(云环境)                       │
│  [Node1] [Node2]  →  [Node1] [Node2] [Node3]       │
│                                                     │
└─────────────────────────────────────────────────────┘

HPA(Horizontal Pod Autoscaler)

HPA 根据指标自动调整 Pod 副本数,是最常用的 Autoscaler。

前置条件

需要安装 Metrics Server 来收集 CPU/内存指标:

bash
# Docker Desktop 可能已预装,检查一下
kubectl get deployment metrics-server -n kube-system

# 如果没有,安装
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

# 验证
kubectl top nodes
kubectl top pods

创建 HPA

bash
# 命令方式
kubectl autoscale deployment web-app \
  --min=2 \
  --max=10 \
  --cpu-percent=50

# 查看 HPA
kubectl get hpa

YAML 方式

yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: web-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web-app
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50    # CPU 使用率超过 50% 就扩容
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 70    # 内存使用率超过 70% 就扩容
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 60    # 扩容稳定窗口
      policies:
      - type: Pods
        value: 2                        # 每次最多扩 2 个 Pod
        periodSeconds: 60
    scaleDown:
      stabilizationWindowSeconds: 300   # 缩容稳定窗口(5分钟)
      policies:
      - type: Percent
        value: 10                       # 每次最多缩 10%
        periodSeconds: 60

HPA 工作原理

每 15 秒检查一次指标


期望副本数 = ceil(当前副本数 × (当前指标值 / 目标指标值))

    例:当前 3 副本,CPU 80%,目标 50%
    期望 = ceil(3 × 80/50) = ceil(4.8) = 5


调整 Deployment 的 replicas

压力测试体验 HPA

bash
# 创建测试 Deployment(必须设置 resources.requests)
kubectl apply -f - <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: php-apache
spec:
  replicas: 1
  selector:
    matchLabels:
      run: php-apache
  template:
    metadata:
      labels:
        run: php-apache
    spec:
      containers:
      - name: php-apache
        image: registry.k8s.io/hpa-example
        ports:
        - containerPort: 80
        resources:
          requests:
            cpu: 200m
          limits:
            cpu: 500m
---
apiVersion: v1
kind: Service
metadata:
  name: php-apache
spec:
  selector:
    run: php-apache
  ports:
  - port: 80
EOF

# 创建 HPA
kubectl autoscale deployment php-apache --cpu-percent=50 --min=1 --max=10

# 持续监控 HPA
kubectl get hpa php-apache -w

# 另一个终端:施加压力
kubectl run -i --tty load-generator --rm --image=busybox -- \
  /bin/sh -c "while true; do wget -q -O- http://php-apache; done"

# 观察 Pod 数量增长
kubectl get pods -l run=php-apache -w

# 停止压力后,等待几分钟观察缩容

VPA(Vertical Pod Autoscaler)

VPA 自动调整 Pod 的 CPU 和内存请求/限制。需要额外安装。

yaml
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: web-vpa
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web-app
  updatePolicy:
    updateMode: "Auto"       # Auto / Off / Initial
  resourcePolicy:
    containerPolicies:
    - containerName: '*'
      minAllowed:
        cpu: 100m
        memory: 50Mi
      maxAllowed:
        cpu: 2
        memory: 2Gi

注意:HPA 和 VPA 不要同时基于同一个指标使用。


Cluster Autoscaler(集群自动扩缩容)

当 Pod 因资源不足无法调度时,自动向云厂商申请新节点。 Pod 减少后,将空闲节点归还。

在阿里云 ACK 上:

  • 在控制台开启"弹性伸缩"
  • 配置节点池的最小/最大节点数
  • Cluster Autoscaler 会自动管理

下一步

Phase 8 - K8s 安全