ReplicaSet specification

Similar to what we have learned about pods, Kubernetes also allows us to either imperatively or declaratively define and create a ReplicaSet. Since the declarative approach is by far the recommended one in most cases, we're going to concentrate on this approach. Here is a sample specification for a Kubernetes ReplicaSet:

apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: rs-web
spec:
selector:
matchLabels:
app: web
replicas: 3
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:alpine
ports:
- containerPort: 80

This looks an awful lot like the pod specification we introduced earlier. Let's concentrate on the differences, then. First, on line 2, we have the kind which was Pod and is now ReplicaSet. Then, on lines 6–8, we have a selector which determines the pods that will be part of the ReplicaSet. In this case, it is all pods that have a label app with the value web. Then, on line 9, we define how many replicas of the pod we want to run; three, in this case. Finally, we have the template section which first defines the metadata and then the spec which defines the containers that run inside the pod. In our case, we have a single container using the nginx:alpine image and exporting port 80.

The really important elements are the number of replicas and the selector which specifies the set of pods governed by the ReplicaSet.

In our  ch12 folder, we have a file called replicaset.yaml that contains the preceding specification exactly. Let's use this file to create the ReplicaSet:

$ kubectl create -f replicaset.yaml
replicaset "rs-web" created

If we list all the ReplicaSets in the cluster, we get this (rs is a shortcut for replicaset):

$ kubectl get rs
NAME DESIRED CURRENT READY AGE
rs-web 3 3 3 51s

In the preceding output, we can see that we have a single ReplicaSet called rs-web whose desired state is three (pods). The current state also shows three pods and all three pods are ready. We can also list all pods in the system and we get this:

$ kubectl get pods
NAME READY STATUS RESTARTS AGE
rs-web-6qzld 1/1 Running 0 4m
rs-web-frj2m 1/1 Running 0 4m
rs-web-zd2kt 1/1 Running 0 4m

Here, we see our three expected pods. The names of the pods are using the name of the ReplicaSet with a unique ID appended for each pod. In the READY column, we see how many containers are defined in the pod and how many of them are ready. In our case, we have only a single container per pod and in each case, it is ready. Thus, the overall status of the pod is Running. We also see how many times each pod had to be restarted. In our case, we did not have any restarts yet.