Skip to content

配置 Kubernetes Auto-Scaling

中等 约 30 分钟

你将构建什么

Horizontal Pod Autoscaler (HPA) 那个 automatically 添加 or 移除 Pods based on CPU utilization, keeping 你的 application responsive under varying 加载.

学习目标

  • 理解 horizontal auto-scaling 概念
  • 部署 Kubernetes Metrics 服务器
  • 创建 Horizontal Pod Autoscaler
  • 测试 scaling 通过 generating 加载

前置要求

  • Kubernetes cluster 使用 kubectl
  • application deployed 使用 CPU resource 请求
  • 基础理解的 Kubernetes 部署

步骤

  1. 1

    安装 Metrics 服务器

    Metrics 服务器 provides resource usage 数据到 Kubernetes. 安装它 如果不 already present in 你的 cluster.

    代码
    kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

    预期结果

    Metrics 服务器是 运行. 验证使用 kubectl 顶部节点.

  2. 2

    Ensure 部署有 resource 请求

    HPA 需要 CPU resource 请求到 工作. 制作确定你的部署 specifies resources.请求.cpu.

    代码
    resources:
      requests:
        cpu: 100m
        memory: 128Mi
      limits:
        cpu: 500m
        memory: 256Mi

    预期结果

    部署有 CPU 请求设置, 哪个 HPA 将 use for scaling decisions.

  3. 3

    创建 Horizontal Pod Autoscaler

    创建 HPA 那个 scales 之间 2 and 10 replicas, targeting 50% CPU utilization.

    代码
    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: my-app-hpa
    spec:
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: my-app
      minReplicas: 2
      maxReplicas: 10
      metrics:
        - type: Resource
          resource:
            name: cpu
            target:
              type: Utilization
              averageUtilization: 50

    预期结果

    HPA 是创建 and 开始 monitoring CPU usage.

  4. 4

    Generate 加载 and watch scaling

    Generate 加载 on 你的 application 到触发 scaling. Watch HPA 添加 Pods as CPU usage increases.

    代码
    kubectl get hpa -w
    # In another terminal, generate load:
    kubectl run -i --tty load-generator --rm --image=busybox -- /bin/sh -c "while true; do wget -q -O- http://my-app-service; done"

    预期结果

    As CPU usage rises, HPA scales 上 Pods. 当加载停止, 它 scales 后面下.

  5. 5

    添加健康检查端点

    为应用添加 /health 端点返回 200 OK,供编排系统(Kubernetes、负载均衡器)探测存活。健康检查是生产部署的基础设施。

    代码
    # app.py (Flask example)
    from flask import Flask, jsonify
    app = Flask(__name__)
    
    @app.route("/health")
    def health():
        return jsonify({"status": "ok"}), 200
    
    @app.route("/ready")
    def ready():
        # Check DB connection etc.
        return jsonify({"ready": True}), 200

    预期结果

    curl localhost:5000/health 返回 {"status":"ok"} 和 200 状态码。

自己动手试试

你学到了什么

你配置 horizontal auto-scaling 那个 automatically adjusts 数字的 Pods based on 加载. Auto-scaling 是键 到 handling 变量 traffic efficiently — 你保存 resources 当 demand 是低 and scale 上当 demand 是高.

相关资源

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题