Autoscale a Deployment with an HPA (1 → 5)
A CPU-bound web app needs to scale out under load and back in when idle. With metrics-server already running, create a HorizontalPodAutoscaler that scales the Deployment between 1 and 5 replicas on CPU.
The situation
The php-apache Deployment in kubelings runs a single replica and falls over
under load. metrics-server is already collecting CPU usage. You need a
HorizontalPodAutoscaler so the app scales out on CPU and back in when idle.
┌──────────┐
│CPU usage │
│ │
└──────────┘
│ ▲
│ └───┐
│ │
metrics-server │
│ │
▼ │
┌───────────────┐ │
│HPA target 50% │ │
│ │ │
└───────────────┘ │
│ │
scale out or in│
│ │
▼ │
┌────────────────┐
│replicas 1 to 5 │
│ │
└────────────────┘
Your task
Create an HPA named php-apache that:
- Targets the
php-apacheDeployment. minReplicas: 1,maxReplicas: 5.- Scales on CPU (e.g. target 50% average utilization).
kubectl -n kubelings top pods # metrics-server is live
kubectl -n kubelings get hpa
Hint
kubectl -n kubelings autoscale deploy php-apache --cpu=50% --min=1 --max=5
(Generate a load and watch with kubectl -n kubelings get hpa -w to see it climb.)
Solution
Approach
An HPA needs (a) metrics-server (already running) and (b) a CPU request on the
target pods to compute utilization against — php-apache has requests.cpu: 200m.
Create the HPA
Imperative (simplest):
kubectl -n kubelings autoscale deploy php-apache --cpu=50% --min=1 --max=5
or declarative (autoscaling/v2):
kubectl -n kubelings apply -f - <<'EOF'
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: php-apache
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: php-apache
minReplicas: 1
maxReplicas: 5
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
EOF
Verify
kubectl -n kubelings get hpa php-apache
# generate load:
kubectl -n kubelings run load --rm -it --image=ghcr.io/iximiuz/labs/busybox:latest -- \
sh -c "while true; do wget -q -O- http://php-apache; done"
kubectl -n kubelings get hpa php-apache -w # replicas climb toward 5
- Previous lesson
- CronJob Pileup: fix the concurrencyPolicy
- Next lesson
- OOMKilled CrashLoop: right-size the memory limit