Kubernetes Horizontal Pod Autoscaler (HPA): Autoscale Your Application Workloads using Kubernetes

 


Kubernetes Horizontal Pod Autoscaler (HPA) Setup

Prerequisites:  metrics-server

For Minikube users: 

minikube addons enable metrics-server 

For kubernetes cluster:

kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

1.  At first create the deployments.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
name: web-servers
labels:
app: web-servers
spec:
selector:
matchLabels:
app: web-servers
replicas: 1
template:
metadata:
labels:
app: web-servers
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
resources:
limits:
cpu: 30m
memory: 50Mi
requests:
cpu: 10m
memory: 10Mi

2. Then create the service.yaml. Here, i am using NodePort

apiVersion: v1
kind: Service
metadata:
labels:
app: web-servers
name: web-servers
namespace: default
spec:
ports:
- name: web-servers-port
port: 80
selector:
app: web-servers
sessionAffinity: None
type: NodePort

3. Then finally create the Horizontal Pod Autoscaler in autoscaler.yaml. Here, I have definded 20%  threshold for CPU  usage and 30Mi threshold for Memory. Minimum replica is 1 and Maximum replica is 3. You can modifiy it according to your needs. That means the autoscaling will be triggered after the usage of this threshold values.

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-servers
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-servers
minReplicas: 1
maxReplicas: 3
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 20
- type: Resource
resource:
name: memory
target:
type: AverageValue
averageValue: 30Mi

 Then apply these yamls

 kubectl apply -f .

 After that, check the nodeport

 kubectl get svc

 Finally test the autoscaler using hey command. Check the master node ip or if you are using  minikube then type minikube ip to get the ip

 hey -n 10000 -c 5 http://192.168.59.100:32681

Video Tutorial



Download Coding Interview Book and Get More Tutorials for Coding and Interview Solution: Click Here

Download System Design Interview Book and Get More Tutorials and Interview Solution: Click Here

Do you need more Guidance or Help? Then Book 1:1 Quick Call with Me: Click Here

Share on Google Plus

About Ashadullah Shawon

I am Ashadullah Shawon. I am a Software Engineer. I studied Computer Science and Engineering (CSE) at RUET. I Like To Share Knowledge. Learn More: Click Here
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment