🎓 A1Learner
🔍
0 of 51 lessons completed

Kubernetes: Horizontal Pod Autoscaler

The Horizontal Pod Autoscaler changes the number of pods as demand changes. It adds pods when load rises and removes pods when load falls.

Turn on the metrics server

The metrics server is off by default. Turn it on before you create the autoscaler.

minikube addons enable metrics-server

One autoscaler, one target

The autoscaler watches one Deployment. It compares real CPU use with the target you set.

kubectl autoscale deployment web --cpu-percent=50 --min=2 --max=6

Read the autoscaler

The targets column shows the current use against the target. The replicas column shows the current pod count.

kubectl get hpa web

The same autoscaler as YAML

YAML stores the same settings as the command. It keeps the autoscaler with the rest of the app files.

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: web
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web
  minReplicas: 2
  maxReplicas: 6
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50

Three scalers, three jobs

Each scaler works at a different level. The autoscaler detail shows the pod count limits it controls.

kubectl describe hpa web | grep -E 'Min replicas|Max replicas|Reference'

Example

kubectl autoscale deployment web --cpu-percent=50 --min=2 --max=6
kubectl get hpa web

Key points

  • Horizontal Pod Autoscaler: a controller that changes replica count from CPU or memory use
  • Use the metrics server to supply the CPU and memory numbers the autoscaler reads
  • Set a target CPU use such as 50 percent of the requested CPU
  • Set a minimum replica count so the app never drops to zero pods
  • Set a maximum replica count so a surge cannot run away with your cluster
  • The Horizontal Pod Autoscaler changes pod count while the Vertical Pod Autoscaler changes pod size
  • The cluster autoscaler changes node count while the Horizontal Pod Autoscaler changes pod count

In this example, the first command creates an autoscaler for the web Deployment. It sets the CPU target to 50 percent with two pods at least and six pods at most. The second command reads the autoscaler back. The output shows the current use at 12 percent against the 50 percent target. It also shows two replicas running, which matches the minimum.

Note

The autoscaler reacts to measured load, so it cannot predict a sudden spike before it happens.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does the Horizontal Pod Autoscaler change when CPU use rises above its target?