Use horizontal pod autoscaling (HPA)

Updated at:

Enable the Horizontal Pod Autoscaler (HPA) to automatically scale your pods based on CPU utilization, memory usage, or custom metrics. HPA increases the number of pod replicas to handle traffic spikes and decreases the count during idle periods to save resources automatically. This feature is ideal for applications with fluctuating workloads that require frequent scaling, such as e-commerce platforms, online education services, and financial applications.

Prerequisites

Create an HPA application in the console

  1. Log on to the ACK console. In the left navigation pane, click Clusters.

  2. On the Cluster List page, click the name of the destination cluster or click Details in the Actions column.

  3. In the left navigation pane of the cluster management page, choose Workload > Deployments.

  4. On the Deployments page, click Create from Image.

  5. On the Create page, follow the on-screen instructions to complete the basic application information, container, Service, and scaling configurations to create a Deployment that supports HPA.

    For more information about the procedure and the configuration items, see Create a stateless application from an image. The following section describes only the main configuration items.

    • Basic Information: Configure the name of the application, the number of replicas, and other settings.

    • Container: Configure the image and the required CPU and memory resources.

      Important

      Set the required Request resources for the application. Otherwise, the containers cannot be scaled automatically.

    • Advanced Settings:

      • In the Access Control section, find Services and click the corresponding Create to configure the Service.

      • In the Scaling section, find HPA and select Enabled to configure the scaling conditions and parameters.

        • Metric: CPU and memory are supported. The metric type must be the same as the type of the required resources that you configured. If you specify both the CPU and memory resource types, HPA performs a scaling operation when it detects that either metric reaches the scaling threshold.

        • Condition : The percentage of resource usage. When the usage exceeds this value, the containers start to scale out. For more information about the horizontal pod autoscaling algorithm, see Algorithm details .

        • Max. Replicas: The maximum number of replicas to which the Deployment can be scaled out. This value must be greater than the minimum number of replicas.

        • Min. Replicas: The minimum number of replicas to which the Deployment can be scaled in. This value must be an integer greater than or equal to 1.

Create an HPA application by using kubectl

You can also use an orchestration template to manually create an HPA and bind it to the target Deployment. We recommend creating only one HPA per workload. This example shows how to deploy an Nginx application that supports HPA.

  1. Create a file named nginx.yml and copy the following content into it.

    Important

    To use HPA, you must set the request resources for the pods. Otherwise, HPA cannot run.

    apiVersion: apps/v1 
    kind: Deployment
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      replicas: 2
      selector:
        matchLabels:
          app: nginx  
      template:
        metadata:
          labels:
            app: nginx
        spec:
          containers:
          - name: nginx
            image: nginx:1.7.9 # Replace with your actual <image_name:tags>.
            ports:
            - containerPort: 80
            resources:
              requests:         # You must set requests. Otherwise, HPA cannot calculate metrics, and the status will be 'unknown'.
                cpu: 500m
  2. Run the following command to create the Nginx application.

    kubectl apply -f nginx.yml
  3. Create a file named hpa.yml and copy the following content into it to create the HPA.

    Use scaleTargetRef to specify the target object for the HPA. In this example, the HPA is bound to a Deployment named nginx and triggers a scaling operation when the average CPU utilization of the containers in all Pods reaches 50%.

    Kubernetes 1.24 and later

    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: nginx-hpa
    spec:
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: nginx
      minReplicas: 1  # The minimum number of replicas for the Deployment. Must be an integer greater than or equal to 1.
      maxReplicas: 10  # The maximum number of replicas for the Deployment. Must be greater than minReplicas.
      metrics:
      - type: Resource
        resource:
          name: cpu
          target:
            type: Utilization
            averageUtilization: 50 # The target average resource utilization, which is the ratio of average resource usage to the requested resource amount.
                   

    Kubernetes before 1.24

    apiVersion: autoscaling/v2beta2
    kind: HorizontalPodAutoscaler
    metadata:
      name: nginx-hpa
    spec:
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: nginx
      minReplicas: 1  # Must be an integer greater than or equal to 1.
      maxReplicas: 10  # Must be greater than the minimum number of replicas.
      metrics:
      - type: Resource
        resource:
          name: cpu
          target:
            type: Utilization
            averageUtilization: 50
                   

    If you need to specify both CPU and memory metrics, you can specify both cpu and memory resource types in the metrics field instead of creating two HPAs. When the HPA detects that any of the metrics reaches the scaling threshold, it will perform a scaling operation.

    metrics:
      - type: Resource
        resource:
          name: cpu
          target:
            type: Utilization
            averageUtilization: 50
      - type: Resource
        resource:
          name: memory
          target:
            type: Utilization
            averageUtilization: 50
  4. Run the following command to create the HPA.

    kubectl apply -f hpa.yml

    At this point, run the kubectl describe hpa <HPA name> command. In this example, the HPA name is nginx-hpa. The expected output is the following warning message, which indicates that the HPA is still being deployed. You can run the kubectl get hpa command to check the status of the HPA.

    Warning  FailedGetResourceMetric       2m (x6 over 4m)  horizontal-pod-autoscaler  missing request for cpu on container nginx in pod default/nginx-deployment-basic-75675f5897-mqzs7
    
    Warning  FailedComputeMetricsReplicas  2m (x6 over 4m)  horizontal-pod-autoscaler  failed to get cpu utilization: missing request for cpu on container nginx in pod default/nginx-deployment-basic-75675f5
  5. After the HPA is created and the Pod meets the scaling conditions (in this example, the CPU utilization of the Nginx Pod exceeds 50%), run the kubectl describe hpa <HPA-name> command again to view the horizontal scaling status.

    The following output indicates that the HPA is running correctly.

    Type    Reason             Age   From                       Message
      ----    ------             ----  ----                       -------
      Normal  SuccessfulRescale  5m6s  horizontal-pod-autoscaler  New size: 1; reason: All metrics below target