Implementing Horizontal Pod Autoscaling
1. Creating HPA
kubectl autoscale deploy web --min=2 --max=10 --cpu-percent=70
| Flag | Effect |
--min / --max | Replica bounds |
--cpu-percent | Target avg CPU utilization (% of request) |
2. Creating HPA from YAML
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: web }
spec:
scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: web }
minReplicas: 2
maxReplicas: 20
metrics:
- type: Resource
resource: { name: cpu, target: { type: Utilization, averageUtilization: 70 } }
- type: Resource
resource: { name: memory, target: { type: AverageValue, averageValue: 512Mi } }
3. Listing HPAs
kubectl get hpa
kubectl get hpa web -o yaml
| Column | Meaning |
| TARGETS | current / desired |
| MINPODS / MAXPODS | Bounds |
| REPLICAS | Current |
4. Describing HPA Details
| Field | Info |
| Conditions | AbleToScale, ScalingActive, ScalingLimited |
| Events | SuccessfulRescale, FailedGetResourceMetric |
5. Setting Min and Max Replicas
| Field | Detail |
| minReplicas | Floor (default 1; can be 0 in 1.16+ alpha) |
| maxReplicas | Ceiling — required |
6. Using CPU-Based Scaling
metrics:
- type: Resource
resource:
name: cpu
target: { type: Utilization, averageUtilization: 70 }
Note: Utilization is % of requests.cpu. Requires Metrics Server.
7. Using Memory-Based Scaling
| target.type | Meaning |
| Utilization | % of requests.memory |
| AverageValue | Absolute per-pod value |
8. Using Custom Metrics
metrics:
- type: Pods
pods:
metric: { name: requests_per_second }
target: { type: AverageValue, averageValue: "100" }
- type: External
external:
metric:
name: kafka_lag
selector: { matchLabels: { topic: orders } }
target: { type: Value, value: "1000" }
| Type | Source |
| Pods | Per-pod metric (custom.metrics.k8s.io) |
| Object | Metric on a single K8s object |
| External | External system (external.metrics.k8s.io) |
Note: Requires prometheus-adapter or KEDA for non-resource metrics.
9. Configuring Scale Up Behavior
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- { type: Percent, value: 100, periodSeconds: 15 }
- { type: Pods, value: 4, periodSeconds: 15 }
selectPolicy: Max
| Field | Effect |
| policies | Limit add per window |
| selectPolicy | Max / Min / Disabled |
10. Configuring Scale Down Behavior
behavior:
scaleDown:
stabilizationWindowSeconds: 300 # default
policies:
- { type: Percent, value: 10, periodSeconds: 60 }
11. Setting Stabilization Window
| Behavior | Default |
| scaleUp | 0s (immediate) |
| scaleDown | 300s (avoid flapping) |
12. Troubleshooting HPA
| Issue | Cause |
<unknown> target | Metrics Server missing/unreachable |
| No scaling | Pod requests not set; can't compute % |
| Flapping | Stabilization window too short |
| Custom metric fail | prometheus-adapter not configured |