In this blog, we will walk through what a ReplicaSet is, why it is used, and how to create one using a YAML configuration.

What is ReplicaSet?

A ReplicaSet is an object on Kubernetes, which runs identical pods in the desired number. ReplicaSet is managed and controlled by the ReplicaSet controller, which maintains the desired number of replicas you specify.

A ReplicaSet provides:

  • High availability — failed Pods are replaced automatically
  • Scalability — you can scale replicas up or down easily
  • Self-healing — Pods that crash are recreated

Now, let's see about how to create ReplicaSet.

How to create ReplicaSet?

In this example, we are going to deploy three replicas of the Nginx, webserver using ReplicaSet, to do that, create a YAML file replicas.yaml and copy the content below into it

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest       

This YAML file will deploy a ReplicaSet, and the ReplicaSet creates three replicas of the latest Nginx web server on the default namespace.

  • replicas: It defines the desired number of pods.
  • selector: It is used to identify which pods the ReplicaSet should manage. matchLabels the selector  field should be the same as the pod labels.
  • template: It has the pod template. The pod template defines the underlying Pod configuration. It acts as a blueprint for creating new Pods managed by the ReplicaSet.

Important Points (CKA Exam Relevant)

  • The selector.matchLabels must match the labels inside the Pod template.
  • If labels do not match, the ReplicaSet will create Pods but never manage them correctly.

Apply the ReplicaSet

kubectl apply -f replicas.yaml

You can check the status of your ReplicaSet and replica pods using the following command

To verify the ReplicaSet:

kubectl get rs

To check the Pods created by the ReplicaSet:

kubectl get pods -l app=nginx

To see more details:

kubectl describe rs nginx

Scaling the ReplicaSet

You can scale the number of replicas:

kubectl scale rs nginx --replicas=5

You can update the YAML file and reapply it. I used the command there.

Conclusion

I believe this blog gives you a decent understanding of ReplicaSet and how to deploy it.