Kubernetes Tutorial · Workloads · Lesson 9 of 26
Scaling
Change the number of replicas manually, and understand what autoscaling adds.
Manual scaling
kubectl scale deployment/web --replicas=5, or change replicas: in the YAML. Scaling down removes pods;
applications must shut down gracefully on SIGTERM (finish in-flight requests within
terminationGracePeriodSeconds, 30 s by default).
Autoscaling
- HorizontalPodAutoscaler (HPA) changes replicas based on CPU, memory or custom metrics.
- VerticalPodAutoscaler adjusts requests and limits.
- Cluster autoscalers (Cluster Autoscaler, Karpenter) add nodes when pods can't be scheduled.
If you use an HPA, don't also set replicas: in the applied YAML, or every apply fights the autoscaler.
kubectl create namespace demo-scale > /dev/null
trap 'kubectl delete namespace demo-scale --wait=false > /dev/null' EXIT
kubectl -n demo-scale create deployment api --image=busybox:1.37 -- sleep 3600 > /dev/null
for n in 4 1; do
kubectl -n demo-scale scale deployment/api --replicas=$n > /dev/null
kubectl -n demo-scale rollout status deployment/api --timeout=120s > /dev/null
for i in $(seq 60); do # wait until terminating pods are gone
count=$(kubectl -n demo-scale get pods -l app=api -o name | wc -l)
[ "$count" -eq "$n" ] && break; sleep 1
done
echo "replicas=$n -> pods: $count"
done
Output
replicas=4 -> pods: 4 replicas=1 -> pods: 1
Run this on your computer — see “Get Started” for setup.
Test yourself
Why shouldn't an applied Deployment YAML set replicas when an HPA manages it?
HPAs require replicas: 0Each apply would reset the replica count the autoscaler choseIt is invalid YAMLIt disables probes
Show answer
Answer: Each apply would reset the replica count the autoscaler chose
Leave replicas to the HPA (or set it only on creation).