Horizontal Pod Autoscaler (HPA)
The Horizontal Pod Autoscaler automatically scales the number of pods in a Deployment or ReplicaSet based on observed CPU utilization or custom metrics.
HPA is how Kubernetes achieves elastic scaling β your application scales up during traffic spikes and scales down during quiet periods, saving resources.
How HPA Works
Traffic Increases
β
βΌ
ββββββββββββββββ
β HPA polls β (every 15 seconds by default)
β metrics β
ββββββββ¬ββββββββ
β
βΌ
CPU usage > target? ββYesβββΆ Scale up pods
β
No
β
βΌ
CPU usage < target? ββYesβββΆ Scale down pods
β
No
β
βΌ
Do nothing
Creating an HPA
# Quick way
kubectl autoscale deployment my-app --min=2 --max=10 --cpu-percent=70
# Full YAML definition
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
behavior:
scaleUp:
stabilizationWindowSeconds: 60
policies:
- type: Percent
value: 100
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 10
periodSeconds: 60
scaleTargetRef β Which Deployment to scale.
metrics β What to measure (CPU, memory, or custom metrics).
behavior β How fast to scale up and down. Scaling down is slower to avoid flapping.
Prerequisites for HPA
Resource requests must be set β HPA calculates utilization as a percentage of requested resources. Without requests, HPA cannot work.
Metrics server required β Install the metrics server for CPU/memory metrics:
# Install metrics server (Minikube)
minikube addons enable metrics-server
# Install metrics server (standard)
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
Monitoring HPA
# Check HPA status
kubectl get hpa
# Detailed info
kubectl describe hpa my-app-hpa
# Watch in real-time
kubectl get hpa -w