The HorizontalPodAutoscaler changes replica count from observed metrics. This guide installs Metrics Server, deploys a workload with CPU requests, creates an autoscaler, generates load, and watches scale-up and scale-down.
1. Prepare and execute
Confirm the active kubeconfig context and namespace before applying changes. Save commands and manifests in version control without credentials.
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
kubectl -n kube-system rollout status deployment/metrics-server --timeout=3m
kubectl top nodes
kubectl create namespace hpa-lab
kubectl -n hpa-lab create deployment php-apache --image=registry.k8s.io/hpa-example
kubectl -n hpa-lab set resources deployment/php-apache --requests=cpu=200m --limits=cpu=500m
kubectl -n hpa-lab expose deployment php-apache --port=80
2. Declarative configuration
Save the following example in a clearly named YAML file, review it, then use server-side dry-run when the API is available.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: {name: php-apache, namespace: hpa-lab}
spec:
scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: php-apache}
minReplicas: 1
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target: {type: Utilization, averageUtilization: 50}
3. Verify the result
A successful command is not enough. Inspect resource state, conditions, events, endpoints, logs, and an end-to-end request where applicable.
kubectl apply -f hpa.yaml
kubectl -n hpa-lab run load --image=busybox:1.37 --restart=Never --
sh -c 'while true; do wget -q -O- http://php-apache; done'
kubectl -n hpa-lab get hpa,pod -w
kubectl -n hpa-lab describe hpa php-apache
4. Troubleshooting
Unknown metrics means Metrics Server or API aggregation is unhealthy. CPU utilization targets require CPU requests. Autoscaling cannot compensate for a broken readiness probe or insufficient node capacity.
5. Rollback and cleanup
Review the exact target before deleting resources, especially namespaces, claims, Secrets, and cluster-wide add-ons.
kubectl delete namespace hpa-lab
kubectl delete -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
Production checklist
- The active context, namespace, and target version were verified.
- Manifests passed client or server-side validation.
- Resource conditions and recent events show no unresolved error.
- Access, network exposure, resource limits, persistence, and rollback were reviewed.
- Commands and expected output were recorded for the operating team.
References: topic documentation and Kubernetes documentation.