📈 HPA = Automatic Scaling
Traffic changes constantly. Horizontal Pod Autoscaler scales automatically. More pods when needed, less when not.
📝 HPA Setup
# Install metrics-server
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
# Verify metrics-server
kubectl top pods
kubectl top nodes
# Create HPA
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
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
# Create HPA via command
kubectl autoscale deployment web --cpu-percent=70 --min=2 --max=10
# Check HPA status
kubectl get hpa
kubectl describe hpa web-hpa
🎯 Advanced HPA
# Custom metrics (Prometheus)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: custom-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: app
minReplicas: 2
maxReplicas: 20
metrics:
- type: Pods
pods:
metric:
name: http_requests_per_second
target:
type: AverageValue
averageValue: 100
# Multiple metrics
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: multi-metric-hpa
spec:
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 75
- type: Pods
pods:
metric:
name: requests_per_second
target:
type: AverageValue
averageValue: 500
# Behavior configuration
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: behavior-hpa
spec:
behavior:
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 10
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 30
- type: Pods
value: 4
periodSeconds: 30
selectPolicy: Max
💡 HPA Tips
- Set appropriate min/max replicas
- Monitor HPA behavior
- Use custom metrics for business logic
- Consider VPA for vertical scaling
- Test scaling scenarios
“HPA scales automatically. More pods when busy, fewer when idle. Essential for cost optimization.”
