Skip to main content

Lab 12.2 - Horizontal and Vertical Autoscaling

Lab Objectives​

By the end of this lab, you will be able to:

  • Configure a Horizontal Pod Autoscaler (HPA).
  • Understand how HPA works.
  • Test metrics-based autoscaling.
  • Understand the Vertical Pod Autoscaler (VPA).

Estimated Duration​

60-75 minutes

Prerequisites​

  • kubectl installed and configured.
  • Kubernetes cluster with metrics-server.
  • Knowledge of Deployments.

Part 1: Installing metrics-server​

Step 1.1: Install metrics-server​

kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

Verify:

kubectl get deployment metrics-server -n kube-system

Part 2: Creating an HPA​

Step 2.1: Create a Deployment​

Create deployment-hpa.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
name: hpa-app
spec:
replicas: 2
selector:
matchLabels:
app: hpa-app
template:
metadata:
labels:
app: hpa-app
spec:
containers:
- name: app
image: nginx:1.20
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi

Apply:

kubectl apply -f deployment-hpa.yaml

Step 2.2: Create an HPA​

Create hpa.yaml:

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

Apply:

kubectl apply -f hpa.yaml

Part 3: Testing Autoscaling​

Step 3.1: Generate Load​

Create a Pod to generate load:

kubectl run -i --tty load-generator --rm --image=busybox --restart=Never -- /bin/sh -c "while true; do wget -q -O- http://hpa-app-service; done"

Step 3.2: Observe Autoscaling​

Monitor the HPA:

kubectl get hpa hpa-app -w

Monitor the Pods:

kubectl get pods -l app=hpa-app -w

Part 4: VPA (Introduction)​

VPA automatically adjusts Requests and Limits. Installation is more complex and requires an operator.


Lab Summary​

In this lab, you configured horizontal autoscaling with HPA. You tested autoscaling based on CPU usage.


Next Steps​

The next lab will show you how to set up GitOps with ArgoCD.

Lab 12.3: GitOps with ArgoCD


Lab created on: December 2024