#Lab: Kubernetes Horizontal Pod Autoscaling
Automatically scale applications based on resource usage.
#๐ฏ Objectives
- Configure Horizontal Pod Autoscaler (HPA)
- Test autoscaling with load
- Monitor scaling events
#๐ Prerequisites
- Kubernetes cluster with metrics-server
- kubectl configured
#โฑ๏ธ Duration: 30 minutes
#Task 1: Install Metrics Server (5 min)
bash
1# Check if metrics-server is running
2kubectl get pods -n kube-system | grep metrics
3
4# If not installed (minikube)
5minikube addons enable metrics-server
6
7# Or install manually
8kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
9
10# Verify metrics work
11kubectl top nodes
12kubectl top pods -A#Task 2: Deploy Test Application (5 min)
diagram
cat << 'EOF' | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
name: php-apache
spec:
replicas: 1
selector:
matchLabels:
app: php-apache
template:
metadata:
labels:
app: php-apache
spec:
containers:
- name: php-apache
image: registry.k8s.io/hpa-example
ports:
- containerPort: 80
resources:
requests:
cpu: 200m
limits:
cpu: 500m
---
apiVersion: v1
kind: Service
metadata:
name: php-apache
spec:
selector:
app: php-apache
ports:
- port: 80
EOF
# Verify deployment
kubectl get pods
kubectl get svc php-apache#Task 3: Create HPA (5 min)
bash
1# Create HPA via command
2kubectl autoscale deployment php-apache \
3 --cpu-percent=50 \
4 --min=1 \
5 --max=10
6
7# Or via manifest
8cat << 'EOF' | kubectl apply -f -
9apiVersion: autoscaling/v2
10kind: HorizontalPodAutoscaler
11metadata:
12 name: php-apache
13spec:
14 scaleTargetRef:
15 apiVersion: apps/v1
16 kind: Deployment
17 name: php-apache
18 minReplicas: 1
19 maxReplicas: 10
20 metrics:
21 - type: Resource
22 resource:
23 name: cpu
24 target:
25 type: Utilization
26 averageUtilization: 50
27EOF
28
29# Check HPA status
30kubectl get hpa#Task 4: Generate Load (10 min)
Open a new terminal and run:
bash
# Watch HPA scaling
kubectl get hpa php-apache --watchIn another terminal, generate load:
bash
1# Generate load
2kubectl run load-generator --rm -i --tty \
3 --image=busybox \
4 --restart=Never \
5 -- /bin/sh -c "while true; do wget -q -O- http://php-apache; done"Watch the HPA terminal - pods should scale up as CPU increases.
#Task 5: Observe Scaling (5 min)
bash
1# Stop load generator (Ctrl+C)
2
3# Watch scale down (takes a few minutes)
4kubectl get hpa php-apache --watch
5
6# Check events
7kubectl describe hpa php-apache
8
9# View pods
10kubectl get pods -l app=php-apache#โ Success Criteria
- Metrics server running
- HPA created and targeting deployment
- Pods scaled up under load
- Pods scaled down when load removed
#๐งน Cleanup
bash
kubectl delete hpa php-apache
kubectl delete deployment php-apache
kubectl delete service php-apache