What You Will Learn
Intermediate
- What HPA is and how it works
- How to configure it
- Scaling based on CPU and custom metrics
The Horizontal Pod Autoscaler (HPA) automatically scales the number of Pods based on CPU/memory usage or custom metrics. Traffic up = more Pods. Traffic down = fewer Pods.
hpa.yamlyaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 2 # Never fewer than 2
maxReplicas: 10 # Never more than 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70 # Scale if CPU > 70%Terminalbash
# Apply HPA
kubectl apply -f hpa.yaml
# Check HPA status
kubectl get hpa
# NAME REFERENCE TARGETS MIN MAX REPLICAS
# my-app-hpa Deployment/my-app 45%/70% 2 10 2
# Watch it scale
kubectl get hpa -wHPA needs metrics-server
HPA uses the metrics-server to get CPU/memory data. On minikube: minikube addons enable metrics-server. On cloud K8s, it is usually pre-installed.Practical Exercise
Enable metrics: minikube addons enable metrics-server
Create a Deployment with resource requests
Create an HPA (min=2, max=10, target CPU=70%)
Generate load: kubectl run load --image=busybox --rm -it -- /bin/sh -c 'while true; do wget -qO- http://my-app; done'
Watch: kubectl get hpa -w (replicas increase!)
Key Takeaways
- HPA: auto-scales Pods based on metrics.
- Scale up when CPU > threshold. Scale down when low.
- Needs metrics-server for CPU/memory metrics.
- minReplicas and maxReplicas control the range.
- Custom metrics: scale on requests/sec, queue depth, etc.
Comments
Comments
Post a Comment