Create a deployment using the image php-apache and expose it
Lets create the deployment using a yaml file -> php-apache.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: php-apache
spec:
selector:
matchLabels:
run: php-apache
replicas: 1
template:
metadata:
labels:
run: php-apache
spec:
containers:
- name: php-apache
image: k8s.gcr.io/hpa-example
ports:
- containerPort: 80
resources:
limits:
cpu: 500m
requests:
cpu: 200m
---
apiVersion: v1
kind: Service
metadata:
name: php-apache
labels:
run: php-apache
spec:
ports:
- port: 80
selector:
run: php-apache
Create the deployment using kubectl apply command
$ kubectl apply -f php-apache.yaml
deployment.apps/php-apache created
service/php-apache created
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
php-apache-7656945b6b-pzp9h 0/1 ContainerCreating 0 22s
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
php-apache-7656945b6b-pzp9h 1/1 Running 0 51s
Create the horizontal pod autoscaler
$ kubectl autoscale deployment php-apache --cpu-percent=50 --min=1 --max=10
horizontalpodautoscaler.autoscaling/php-apache autoscaled
You can check the current status of the newly-made HorizontalPodAutoscaler, by running:
$ kubectl get hpa
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
php-apache Deployment/php-apache <unknown>/50% 1 10 1 31s
Increase the load: Run the below command in a separate terminal
$ kubectl run -i --tty load-generator --rm --image=busybox:1.28 --restart=Never -- /bin/sh -c "while sleep 0.01; do wget -q -O- http://php-apache; done"
Now on the main terminal run the following command
$ kubectl get hpa php-apache --watch
You should see the higher CPU load and replicas
NAME REFERENCE TARGET MINPODS MAXPODS REPLICAS AGE
php-apache Deployment/php-apache/scale 305% / 50% 1 10 1 3m
NAME REFERENCE TARGET MINPODS MAXPODS REPLICAS AGE
php-apache Deployment/php-apache/scale 305% / 50% 1 10 7 3m
$ kubectl get deployment php-apache
NAME READY UP-TO-DATE AVAILABLE AGE
php-apache 7/7 7 7 19m
Stop generating the load in the terminal where you created the Pod that runs a busybox image, terminate the load generation by typing <Ctrl> + C
$ kubectl get hpa php-apache --watch
NAME REFERENCE TARGET MINPODS MAXPODS REPLICAS AGE
php-apache Deployment/php-apache/scale 0% / 50% 1 10 1 11m
Deployment also shows that it has scaled down
$ kubectl get deployment php-apache
NAME READY UP-TO-DATE AVAILABLE AGE
php-apache 1/1 1 1 27m
Once CPU utilization dropped to 0, the HPA automatically scaled the number of replicas back down to 1