CKA Practice Question 3
CKA Practice Question 3
Question 3: Configure HorizontalPodAutoscaler (HPA)
Scenario:
Create a new HorizontalPodAutoscaler (HPA) named apache-server in the autoscale namespace.
This HPA must target the existing Deployment called apache-server in the autoscale namespace.
Requirements:
- Set the HPA to target 50% CPU usage per Pod
- Configure the HPA to have at minimum 1 Pod and no more than 4 Pods (max)
- Set the downscale stabilization window to 30 seconds
Task Requirements:
- Namespace:
autoscale - HPA Name:
apache-server - Target Deployment:
apache-server - Target CPU: 50%
- Min Replicas: 1
- Max Replicas: 4
- Downscale Stabilization: 30 seconds
Weight: 6%
Solution
Step 1: Set the Context and Namespace
# Switch to the autoscale namespace
kubectl config set-context --current --namespace=autoscale
# Verify you're in the correct namespace
kubectl config view --minify | grep namespaceStep 2: Verify the Target Deployment
Before creating the HPA, verify that the target deployment exists:
# Check if the deployment exists
kubectl get deployment apache-server
# View deployment details
kubectl describe deployment apache-server
# Check current replicas
kubectl get deployment apache-server -o jsonpath='{.spec.replicas}'Expected Output:
NAME READY UP-TO-DATE AVAILABLE AGE
apache-server 1/1 1 1 5mImportant
The deployment must have resource requests defined for CPU. HPA cannot work without CPU requests!
Check if CPU requests are defined:
# Check resource requests
kubectl get deployment apache-server -o jsonpath='{.spec.template.spec.containers[*].resources.requests.cpu}'If no CPU requests are defined, you'll need to add them:
kubectl set resources deployment apache-server --requests=cpu=100mStep 3: Create the HorizontalPodAutoscaler
Method 1: Using kubectl autoscale (Quick)
kubectl autoscale deployment apache-server \
--name=apache-server \
--cpu-percent=50 \
--min=1 \
--max=4 \
-n autoscaleLimitation
The kubectl autoscale command does NOT support setting the downscale stabilization window. You must use YAML for this requirement!
Method 2: Using YAML (Required for full solution)
kubectl apply -f - <<EOF
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: apache-server
namespace: autoscale
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: apache-server
minReplicas: 1
maxReplicas: 4
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
behavior:
scaleDown:
stabilizationWindowSeconds: 30
EOFKey Points
- apiVersion: Use
autoscaling/v2(not v1 or v2beta2) - scaleTargetRef: Points to the deployment to scale
- minReplicas: Minimum number of pods (1)
- maxReplicas: Maximum number of pods (4)
- metrics: Defines CPU utilization target (50%)
- behavior.scaleDown.stabilizationWindowSeconds: Downscale window (30 seconds)
Step 4: Verify the HPA Configuration
# Check HPA status
kubectl get hpa apache-server
# View detailed HPA information
kubectl describe hpa apache-server
# View HPA in YAML format
kubectl get hpa apache-server -o yamlExpected Output:
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
apache-server Deployment/apache-server 0%/50% 1 4 1 30sDetailed Description Output:
Name: apache-server
Namespace: autoscale
Labels: <none>
Annotations: <none>
CreationTimestamp: Fri, 10 Jan 2026 15:07:00 +0700
Reference: Deployment/apache-server
Metrics: ( current / target )
resource cpu on pods (as a percentage of request): 0% (0) / 50%
Min replicas: 1
Max replicas: 4
Behavior:
Scale Down:
Stabilization Window: 30 seconds
Deployment pods: 1 current / 1 desiredStep 5: Test the HPA (Optional but Recommended)
To verify the HPA is working, you can generate load on the apache-server:
# Get the service endpoint (if service exists)
kubectl get svc apache-server
# Create a load generator pod
kubectl run load-generator --image=busybox --restart=Never -- /bin/sh -c "while true; do wget -q -O- http://apache-server; done"
# Watch the HPA in real-time
kubectl get hpa apache-server --watch
# In another terminal, watch the pods
kubectl get pods --watchExpected Behavior:
- As CPU usage increases above 50%, HPA will scale up (up to 4 pods)
- When load decreases, HPA will wait 30 seconds (stabilization window) before scaling down
- HPA will never scale below 1 pod or above 4 pods
Clean up the load generator:
kubectl delete pod load-generatorComplete Solution Summary
Here's the complete workflow:
# 1. Set namespace context
kubectl config set-context --current --namespace=autoscale
# 2. Verify deployment exists
kubectl get deployment apache-server
# 3. Check CPU requests (required for HPA)
kubectl get deployment apache-server -o jsonpath='{.spec.template.spec.containers[*].resources.requests.cpu}'
# 4. If no CPU requests, add them
kubectl set resources deployment apache-server --requests=cpu=100m
# 5. Create HPA with all requirements
kubectl apply -f - <<EOF
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: apache-server
namespace: autoscale
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: apache-server
minReplicas: 1
maxReplicas: 4
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
behavior:
scaleDown:
stabilizationWindowSeconds: 30
EOF
# 6. Verify HPA
kubectl get hpa apache-server
kubectl describe hpa apache-serverBest Practices
1. Always Define Resource Requests
HPA requires CPU/memory requests to be defined in the deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
name: apache-server
spec:
template:
spec:
containers:
- name: apache
image: httpd:2.4
resources:
requests:
cpu: 100m # Required for CPU-based HPA
memory: 128Mi
limits:
cpu: 200m
memory: 256Mi2. Use Metrics Server
HPA requires the Metrics Server to be installed in the cluster:
# Check if Metrics Server is running
kubectl get deployment metrics-server -n kube-system
# Check if metrics are available
kubectl top nodes
kubectl top pods -n autoscaleIf Metrics Server is not installed:
# Install Metrics Server (example)
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml3. Understand HPA API Versions
| Version | Features | Status |
|---|---|---|
autoscaling/v1 | CPU only | Stable (limited) |
autoscaling/v2beta2 | Multiple metrics, behaviors | Deprecated |
autoscaling/v2 | Multiple metrics, behaviors | Stable (recommended) |
Always use autoscaling/v2 for new HPAs!
4. Configure Appropriate Stabilization Windows
behavior:
scaleDown:
stabilizationWindowSeconds: 30 # Wait 30s before scaling down
policies:
- type: Percent
value: 50
periodSeconds: 15
scaleUp:
stabilizationWindowSeconds: 0 # Scale up immediately
policies:
- type: Percent
value: 100
periodSeconds: 15Why Stabilization Windows Matter
- Prevents flapping: Avoids rapid scale up/down cycles
- Saves resources: Reduces unnecessary pod churn
- Improves stability: Gives time for metrics to stabilize
5. Use Multiple Metrics
You can scale based on multiple metrics:
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 70HPA will use the metric that requires the most replicas.
6. Monitor HPA Events
# Check HPA events
kubectl get events --field-selector involvedObject.name=apache-server
# Watch HPA status continuously
kubectl get hpa apache-server --watch
# Check HPA conditions
kubectl get hpa apache-server -o jsonpath='{.status.conditions[*].type}'7. Set Realistic Targets
# Too aggressive (may cause constant scaling)
averageUtilization: 30
# Recommended (allows some headroom)
averageUtilization: 50-70
# Too conservative (may cause performance issues)
averageUtilization: 908. Use Custom Metrics (Advanced)
For production workloads, consider custom metrics:
metrics:
- type: Pods
pods:
metric:
name: http_requests_per_second
target:
type: AverageValue
averageValue: "1000"9. Implement Proper Scaling Policies
behavior:
scaleDown:
policies:
- type: Pods
value: 1
periodSeconds: 60 # Remove max 1 pod per minute
- type: Percent
value: 10
periodSeconds: 60 # Remove max 10% of pods per minute
selectPolicy: Min # Use the policy that scales down the least10. Document HPA Configuration
# Add annotations for documentation
kubectl annotate hpa apache-server \
description="Auto-scales apache-server based on CPU usage" \
target-cpu="50%" \
min-pods="1" \
max-pods="4" \
created-by="candidate@cka2025"Common Pitfalls to Avoid
Common Mistakes
Missing CPU Requests: HPA cannot work without resource requests defined in the deployment
Wrong API Version: Using
autoscaling/v1when you need behavior configuration (useautoscaling/v2)Metrics Server Not Installed: HPA requires Metrics Server to function
Unrealistic Targets: Setting CPU target too low (e.g., 10%) causes constant scaling
No Stabilization Window: Without stabilization, HPA may scale up/down too frequently
Wrong Target Reference: Ensure scaleTargetRef points to the correct deployment
Namespace Mismatch: HPA must be in the same namespace as the target deployment
Conflicting Controllers: Don't manually scale a deployment that has an HPA
Insufficient Permissions: Ensure HPA controller has permissions to scale deployments
Not Testing: Always verify HPA is working by checking
kubectl get hpa
Time-Saving Tips
- Use
kubectl autoscalefor quick creation, then edit for advanced features - Use
kubectl explain hpa.spec.behaviorto check available options - Keep HPA YAML templates ready for common scenarios
- Use
kubectl get hpa --watchto monitor scaling in real-time - Remember: HPA name can match deployment name (makes it easier to remember)
- Use
-o yamlto view existing HPA configuration as reference
Important Notes
- HPA evaluates metrics every 15 seconds by default (configurable)
- Scaling decisions are made every 30 seconds by default
- HPA uses the
--horizontal-pod-autoscaler-sync-periodflag (default: 15s) - Downscaling is more conservative than upscaling (prevents flapping)
- HPA will not scale below minReplicas even if CPU is 0%
- HPA will not scale above maxReplicas even if CPU is 100%
- In the exam, focus on meeting the exact requirements - don't overcomplicate
HPA Behavior Explained
Scaling Algorithm
HPA uses the following formula to calculate desired replicas:
desiredReplicas = ceil[currentReplicas * (currentMetricValue / targetMetricValue)]Example:
- Current replicas: 2
- Current CPU: 80%
- Target CPU: 50%
- Desired replicas: ceil[2 * (80 / 50)] = ceil[3.2] = 4
Stabilization Windows
behavior:
scaleDown:
stabilizationWindowSeconds: 30 # Wait 30s before scaling down
scaleUp:
stabilizationWindowSeconds: 0 # Scale up immediately (default)Why different windows?
- Scale Up: Fast response to increased load (0 seconds)
- Scale Down: Prevent premature scale down (30-300 seconds)
Scaling Policies
behavior:
scaleDown:
policies:
- type: Pods
value: 1
periodSeconds: 60 # Max 1 pod removed per minute
- type: Percent
value: 10
periodSeconds: 60 # Max 10% pods removed per minute
selectPolicy: Min # Choose the most conservative policyTroubleshooting HPA
Issue 1: HPA Shows "Unknown" for Current CPU
Symptom:
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS
apache-server Deployment/apache-server <unknown>/50% 1 4 1Causes:
- Metrics Server not installed
- Pods don't have CPU requests
- Pods are not ready yet
Solution:
# Check Metrics Server
kubectl get deployment metrics-server -n kube-system
# Check CPU requests
kubectl get deployment apache-server -o jsonpath='{.spec.template.spec.containers[*].resources.requests.cpu}'
# Add CPU requests if missing
kubectl set resources deployment apache-server --requests=cpu=100m
# Check pod status
kubectl get podsIssue 2: HPA Not Scaling
Symptom: HPA shows correct metrics but doesn't scale
Causes:
- Already at min/max replicas
- Cooldown period active
- Insufficient cluster resources
Solution:
# Check HPA conditions
kubectl describe hpa apache-server
# Check cluster resources
kubectl top nodes
# Check events
kubectl get events --field-selector involvedObject.name=apache-serverIssue 3: HPA Scaling Too Frequently
Symptom: Pods constantly scaling up and down
Causes:
- No stabilization window
- Target too sensitive
- Workload is bursty
Solution:
# Increase stabilization window
kubectl patch hpa apache-server --type=merge -p '
{
"spec": {
"behavior": {
"scaleDown": {
"stabilizationWindowSeconds": 300
}
}
}
}'
# Adjust target (make less sensitive)
kubectl patch hpa apache-server --type=merge -p '
{
"spec": {
"metrics": [{
"type": "Resource",
"resource": {
"name": "cpu",
"target": {
"type": "Utilization",
"averageUtilization": 70
}
}
}]
}
}'Quick Reference Commands
# Essential commands for this task (in order)
kubectl config set-context --current --namespace=autoscale
kubectl get deployment apache-server
kubectl get deployment apache-server -o jsonpath='{.spec.template.spec.containers[*].resources.requests.cpu}'
# Create HPA with YAML (required for stabilization window)
kubectl apply -f - <<EOF
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: apache-server
namespace: autoscale
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: apache-server
minReplicas: 1
maxReplicas: 4
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
behavior:
scaleDown:
stabilizationWindowSeconds: 30
EOF
# Verify
kubectl get hpa apache-server
kubectl describe hpa apache-serverExam Tips for This Question
Read Carefully: Note all requirements - min/max replicas, CPU target, stabilization window
Time Allocation: This is a 6% question, allocate approximately 7-8 minutes
Use YAML: The
kubectl autoscalecommand cannot set stabilization window - you MUST use YAMLAPI Version: Use
autoscaling/v2(not v1 or v2beta2)Verify Deployment: Check that the target deployment exists before creating HPA
Check CPU Requests: HPA won't work without CPU requests in the deployment
Use kubectl apply: Easier than creating a file and applying it
Verify with describe: Use
kubectl describe hpato confirm all settingsDon't Overthink: The question is straightforward - create HPA with specific parameters
Check Status: Ensure HPA shows metrics (not "unknown") before moving on
Related Concepts
- HorizontalPodAutoscaler (HPA): Automatically scales pods based on metrics
- VerticalPodAutoscaler (VPA): Adjusts CPU/memory requests (not covered in CKA)
- Cluster Autoscaler: Scales cluster nodes (not covered in CKA)
- Metrics Server: Provides resource metrics for HPA
- Resource Requests: Required for HPA to calculate utilization
- Stabilization Window: Prevents rapid scaling changes
Additional Practice
Try these variations to deepen your understanding:
- Create HPA with memory-based scaling instead of CPU
- Configure HPA with both CPU and memory metrics
- Implement custom scaling policies (max pods per period)
- Create HPA with different stabilization windows for scale up/down
- Test HPA behavior under load using stress tools
- Configure HPA with custom metrics (requires custom metrics API)
- Implement HPA with external metrics (e.g., queue length)