Kubernetes HorizontalPodAutoscaler (HPA) YAML example
A HorizontalPodAutoscaler changes a workload’s replica count to hold a metric near a target. This one keeps average CPU around 70% by running between 2 and 10 Pods.
Two details trip people up. The scaleTargetRef must name the workload exactly, and CPU utilization is measured against the container’s CPU request, so an HPA on a container with no request has nothing to calculate from.
What this manifest does
This manifest defines 2 resources in the default namespace: the main thing it runs is 1 Deployment. Let’s walk through it.
Deployment api runs 2 Pods, running myorg/api:2.1.0.
An HorizontalPodAutoscaler (api) keeps replicas between 2 and 10 for the api workload.
Things to know before using it
No topology spread or anti-affinityDeployment api
Deployment "api" has 2 replicas but no spread rules. All Pods could land on one node, a single failure domain. Fix: Add topologySpreadConstraints or podAntiAffinity to spread across zones/nodes.
The full manifest
# A Deployment scaled between 2 and 10 Pods on CPU.
apiVersion: apps/v1
kind: Deployment
metadata:
name: api
spec:
replicas: 2
selector:
matchLabels:
app: api
template:
metadata:
labels:
app: api
spec:
containers:
- name: api
image: myorg/api:2.1.0
ports:
- containerPort: 8080
# The HPA measures CPU as a percentage of this request.
resources:
requests:
cpu: 200m
memory: 256Mi
limits:
cpu: "1"
memory: 512Mi
securityContext:
runAsNonRoot: true
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
readinessProbe:
httpGet:
path: /ready
port: 8080
livenessProbe:
httpGet:
path: /healthz
port: 8080
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: api
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
Stuck on a Kubernetes concept?
Ask anything and get a narrated visual lesson, pitched at your level. Free.
Try an example