Scale pods automatically
In this task you'll add pods automatically when CPU gets busy.
A HorizontalPodAutoscaler (HPA) adds and removes pods to keep average CPU (or memory) near a target. Utilisation is a percentage of each container's request, so pods without requests can't be scaled: the HPA shows unknown.
Set a sensible minimum so you're never on one pod, and a maximum so a bug can't scale you into a big bill. The cluster autoscaler adds nodes when pods don't fit.
Example. SS Kaiser's shop runs 2 pods on a quiet Tuesday and 6 during Saturday's sale, with no one changing anything.
Costs money. This task creates resources that are charged while they exist. Delete them as soon as you finish.
Before you start
You need: An AKS cluster. Time: 15 minutes.
Where to look
- kubectl
- set resources
- autoscale
- get hpa
Steps
- Give the container requests:
kubectl set resources deploy/web --requests=cpu=100m,memory=64Mi. - Create the autoscaler:
kubectl autoscale deploy/web --cpu-percent=60 --min=2 --max=6. - Wait a minute, then
kubectl get hpa: TARGETS shows a percentage, not unknown.
Commands
# Connect kubectl to the cluster first
az aks get-credentials -g <group> -n <cluster>
kubectl set resources deploy/web --requests=cpu=100m,memory=64Mi
kubectl autoscale deploy/web --cpu-percent=60 --min=2 --max=6
kubectl get hpa -w
Watch out for
- Cost
- More pods may need more nodes; set a maximum you can afford.
- Security
- Scaling isn't protection against attacks; rate limiting and a WAF are.
- Common mistakes
- No CPU requests (the HPA can't calculate), and max replicas larger than the nodes can hold.
Clean up
kubectl delete hpa web removes the autoscaler.
Words to know
- Request
- The CPU and memory a container is guaranteed; the scheduler uses it to place pods.
- HPA
- Scales the number of pods on a metric.
- Cluster autoscaler
- Scales the number of nodes when pods can't be scheduled.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On