How to Create a ReplicaSet on Kubernetes

In this blog, we are going to look what is ReplicaSet on Kubernetes and hands-on.

If you want to run a certain number of identical Pods always, we can use the ReplicaSet object.

In this, If one Pod is deleted or removed then another Pod will be up and running in the same place.

How to Create a Replica Set

We have to create a manifest to deploy a ReplicaSet and for this, I am using an Nginx image.

cat << EOF > replicaset.yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: nginx
  labels:
    app: nginx
spec:

  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx-container
        image: nginx
EOF

In this manifest, spec.template is used for the creation of the new Pod when the existing one fails.

kubectl apply -f replicaset.yaml
kubectl get replicasets
replicaset

The desired number of Pods is always running.

kubectl get pods
list pods

Testing Replica Set

I am going to delete a Pod from this list and see how many Pods will remain.

kubectl delete pod nginx-h6lp2
list pods

As I said like when a Pod fails a new Pod will be created and also this happens based on the labels, then what happens if we create another Pod with the same label?

kubectl run test-pod --image nginx --labels app=nginx

You can successfully deploy this command but the Pod will not actually be created because the desired state is already present in the cluster.

list pods

Let’s think of another situation, if a Pod is running in the cluster with the labels app: nginx, now, if we create a ReplicaSet with same labels and 3 replicas what happens?

kubectl get pods --show-labels
list pods

Now, I am deploying the same ReplicaSet manifest that we have created already.

kubectl apply -f replicaset.yaml

Only two more Pods will be created even if we mention the replication 3 on the manifest.

list pods

How to Scale the ReplicaSet

Scaling is a very simple process on the ReplicaSet, we can edit the manifest or we can use the imperative command to achieve that.

To scale the ReplicaSet from three to ten, use the following command.

kubectl scale replicaset nginx --replicas 10

nginx is the ReplicaSet name.

list pods

    0 Shares:
    Leave a Reply

    Your email address will not be published. Required fields are marked *

    You May Also Like