> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Lab Solution ReplicaSets optional

> Step-by-step ReplicaSet lab solution demonstrating Kubernetes ReplicaSet behavior, debugging commands, common errors and fixes including image pull, API version, selector mismatches, scaling and pod recreation

This lesson walks through the ReplicaSet lab solution step-by-step, preserving the lab question order and showing the exact commands and sample outputs used to inspect and fix the resources. Use this as a reference to understand ReplicaSet behavior, debugging steps, and common fixes.

Quick reference - common commands:

| Action | Command |
| - | - |
| List pods | `kubectl get pods` |
| List ReplicaSets | `kubectl get replicaset` or `kubectl get rs` |
| Describe ReplicaSet | `kubectl describe replicaset <name>` |
| Describe Pod | `kubectl describe pod <name>` |
| Create from file | `kubectl create -f <file>` |
| Edit resource | `kubectl edit rs <name>` |
| Scale ReplicaSet | `kubectl scale rs <name> --replicas=<n>` |
| Watch pods | `kubectl get pods --watch` |

***

## 1) How many pods exist on the system?

Run:

```bash theme={null}
kubectl get pods
```

Initial output:

```console theme={null}
No resources found in default namespace.
```

Conclusion: there are 0 pods initially.

***

## 2) How many ReplicaSets exist on the system?

Run:

```bash theme={null}
kubectl get replicaset
```

Initial output:

```console theme={null}
No resources found in default namespace.
```

Conclusion: there are 0 ReplicaSets initially.

Later, after a ReplicaSet is created, it can be observed:

```bash theme={null}
kubectl get replicaset
```

Example output:

```console theme={null}
NAME               DESIRED   CURRENT   READY   AGE
new-replica-set    4         4         0       9s
```

***

## 3) What is the desired number of pods in the new ReplicaSet?

From the `kubectl get replicaset` output:

* Desired = 4

Answer: 4

***

## 4) What image is used to create the pods in the new ReplicaSet?

To inspect the ReplicaSet template:

```bash theme={null}
kubectl describe replicaset new-replica-set
```

Relevant excerpt:

```console theme={null}
Name:         new-replica-set
Namespace:    default
Selector:     name=busybox-pod
Replicas:     4 current / 4 desired
Pods Status:  0 Running / 4 Waiting / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  name=busybox-pod
  Containers:
    busybox-container:
      Image:        busybox777
      Command:
        sh
        -c
        echo Hello Kubernetes! && sleep 3600
Events:
  Normal   SuccessfulCreate   60s    replicaset-controller   Created pod: new-replica-set-7r2qw
  Normal   SuccessfulCreate   60s    replicaset-controller   Created pod: new-replica-set-wkzjh
  Normal   SuccessfulCreate   60s    replicaset-controller   Created pod: new-replica-set-tn2mp
  Normal   SuccessfulCreate   60s    replicaset-controller   Created pod: new-replica-set-vpkh8
```

From the pod template, the image is `busybox777`.

Answer: `busybox777`

***

## 5) How many pods are Ready in the new ReplicaSet?

From the `kubectl get replicaset` / `kubectl describe` output:

* Ready = 0

So none of the pods are Ready.

***

## 6) Why are the pods not Ready?

Inspect a failing pod to find the root cause:

```bash theme={null}
kubectl describe pod new-replica-set-7r2qw
```

Relevant excerpt:

```console theme={null}
Containers:
  busybox-container:
    Command:
      sh
      -c
      echo Hello Kubernetes! && sleep 3600
    State:          Waiting
      Reason:       ImagePullBackOff
      Ready:        False
    Restart Count: 0
Events:
  Normal   Scheduled  2m23s            default-scheduler  Successfully assigned default/new-replica-set-7r2qw to controlplane
  Normal   Pulling    46s (x4 over 2m23s) kubelet         Pulling image "busybox777"
  Warning  Failed     46s (x4 over 2m22s) kubelet         Failed to pull image "busybox777": rpc error: code = Unknown desc = failed to pull and unpack image "docker.io/library/busybox777:latest": failed to resolve reference "docker.io/library/busybox777:latest": pull access denied, repository does not exist or may require authorization: server message: insufficient_scope: authorization failed
  Warning  Failed     34s (x6 over 2m21s) kubelet         Error: ImagePullBackOff
  Normal   BackOff    23s (x7 over 2m21s) kubelet         Back-off pulling image "busybox777"
```

Reason: the kubelet cannot pull image `busybox777` — the repository does not exist (invalid image name), causing ImagePullBackOff. Therefore pods are not Ready.

***

## 7) Delete a pod from the ReplicaSet and observe behavior

Delete one pod:

```bash theme={null}
kubectl delete pod new-replica-set-wkzjh
```

Then list pods:

```bash theme={null}
kubectl get pods
```

Example output after deletion:

```console theme={null}
NAME                      READY   STATUS         RESTARTS   AGE
new-replica-set-hcmbw     0/1     ErrImagePull   0          17s
new-replica-set-vpkh8     0/1     ErrImagePull   0          3m26s
new-replica-set-7r2qw     0/1     ErrImagePull   0          3m26s
new-replica-set-tn2mp     0/1     ErrImagePull   0          3m26s
```

Explanation: Deleting a pod managed by a ReplicaSet causes the ReplicaSet controller to immediately create a replacement to maintain the desired count. That's why you still see four pods even after deleting one.

***

## 8) Create a ReplicaSet from a definition file and fix apiVersion issue

List files in `/root`:

```bash theme={null}
ls /root
# replicaset-definition-1.yaml  replicaset-definition-2.yaml  sample.yaml
```

Attempt to create the first definition:

```bash theme={null}
kubectl create -f /root/replicaset-definition-1.yaml
```

Error:

```console theme={null}
error: unable to recognize "/root/replicaset-definition-1.yaml": no matches for kind "ReplicaSet" in version "v1"
```

Inspect the file:

```yaml theme={null}
# /root/replicaset-definition-1.yaml
apiVersion: v1
kind: ReplicaSet
metadata:
  name: replicaset-1
spec:
  replicas: 2
  selector:
    matchLabels:
      tier: frontend
  template:
    metadata:
      labels:
        tier: frontend
    spec:
      containers:
      - name: nginx
        image: nginx
```

Problem: `apiVersion` is set to `v1` but ReplicaSet is in the `apps` API group (`apps/v1`).

Discover the correct API with:

```bash theme={null}
kubectl explain replicaset
```

Fix the file by updating `apiVersion` to `apps/v1`, then create it:

```bash theme={null}
# Update apiVersion to apps/v1 in replicaset-definition-1.yaml
kubectl create -f /root/replicaset-definition-1.yaml
```

Success:

```console theme={null}
replicaset.apps/replicaset-1 created
```

<Callout icon="lightbulb" color="#1CB2FE">
  ReplicaSet belongs to the `apps` API group. Always use `apiVersion: apps/v1`. Use `kubectl explain <kind>` to discover the correct API version and available fields.
</Callout>

***

## 9) Fix the second definition file: selector vs template labels

Attempt to create the second file:

```bash theme={null}
kubectl create -f replicaset-definition-2.yaml
```

Error:

```console theme={null}
The ReplicaSet "replicaset-2" is invalid: spec.template.metadata.labels: Invalid value: map[string]string{"tier":"nginx"}: `selector` does not match template `labels`
```

Inspect `replicaset-definition-2.yaml` (excerpt):

```yaml theme={null}
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: replicaset-2
spec:
  replicas: 2
  selector:
    matchLabels:
      tier: frontend
  template:
    metadata:
      labels:
        tier: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
```

Problem: `spec.selector.matchLabels` is `tier: frontend` while the Pod template labels are `tier: nginx`. A ReplicaSet's selector must match the Pod template labels so it can manage the created pods.

Fix: make `selector.matchLabels` and `template.metadata.labels` match (for example, set both to `tier: frontend`), then create:

```bash theme={null}
kubectl create -f replicaset-definition-2.yaml
```

Success:

```console theme={null}
replicaset.apps/replicaset-2 created
```

Check ReplicaSets:

```bash theme={null}
kubectl get rs
```

Example output:

```console theme={null}
NAME                DESIRED   CURRENT   READY   AGE
new-replica-set     4         4         0       10m
replicaset-1        2         2         2       3m4s
replicaset-2        2         2         2       22s
```

***

## 10) Delete replicaset-1 and replicaset-2

Delete both ReplicaSets:

```bash theme={null}
kubectl delete rs replicaset-1 replicaset-2
```

Output:

```console theme={null}
replicaset.apps "replicaset-1" deleted
replicaset.apps "replicaset-2" deleted
```

***

## 11) Fix the original ReplicaSet to use the correct busybox image

The `new-replica-set` still references the invalid image `busybox777`. Edit the ReplicaSet to correct the container image:

```bash theme={null}
kubectl edit rs new-replica-set
```

In the editor, change the container image from `busybox777` to `busybox`. Example edited snippet:

```yaml theme={null}
spec:
  replicas: 4
  selector:
    matchLabels:
      name: busybox-pod
  template:
    metadata:
      labels:
        name: busybox-pod
    spec:
      containers:
      - command:
        - sh
        - -c
        - echo Hello Kubernetes! && sleep 3600
        image: busybox
        imagePullPolicy: Always
        name: busybox-container
```

Save the change. The ReplicaSet object is updated, but existing pods do not automatically get replaced just because the ReplicaSet pod template changed.

<Callout icon="warning" color="#FF6B6B">
  Editing a ReplicaSet's pod template updates the ReplicaSet object, but it does not replace existing pods. To apply the new template to running pods, either delete the existing pods (so the ReplicaSet recreates them) or recreate the ReplicaSet.
</Callout>

***

## 12) Recreate pods to pick up the new image

Delete the ReplicaSet's pods so the controller will create new pods using the corrected image:

```bash theme={null}
kubectl delete pod new-replica-set-vpkh8 new-replica-set-tn2mp new-replica-set-7r2qw new-replica-set-hcmbw
```

Watch pods being recreated:

```bash theme={null}
kubectl get pods --watch
```

Sample outputs as pods are created and become Running:

```console theme={null}
NAME                             READY   STATUS              RESTARTS   AGE
new-replica-set-8z7z5            0/1     ContainerCreating   0          12s
new-replica-set-f5gth            0/1     ContainerCreating   0          12s
new-replica-set-nsbgx            0/1     ContainerCreating   0          12s
new-replica-set-whhll            0/1     ContainerCreating   0          12s

# A short while later
NAME                             READY   STATUS    RESTARTS   AGE
new-replica-set-f5gth            1/1     Running   0          18s
new-replica-set-nsbgx            1/1     Running   0          18s
new-replica-set-8z7z5            1/1     Running   0          18s
new-replica-set-whhll            1/1     Running   0          18s
```

Verify ReplicaSet ready pods:

```bash theme={null}
kubectl get rs
```

Example output:

```console theme={null}
NAME              DESIRED   CURRENT   READY   AGE
new-replica-set   4         4         4       15m
```

Now the pods are running with the corrected `busybox` image.

Note: When you change a ReplicaSet's pod template, existing pods are not automatically replaced. Deleting the pods causes the ReplicaSet to recreate them with the new template.

***

## 13) Scale the ReplicaSet to 5 pods

Scale with `kubectl scale`:

```bash theme={null}
kubectl scale rs new-replica-set --replicas=5
```

Confirm:

```bash theme={null}
kubectl get pods
```

Example output:

```console theme={null}
NAME                                READY   STATUS    RESTARTS   AGE
new-replica-set-f5gth               1/1     Running   0          55s
new-replica-set-nsbgx               1/1     Running   0          55s
new-replica-set-8z7z5               1/1     Running   0          55s
new-replica-set-whhll               1/1     Running   0          55s
new-replica-set-mwpnz               1/1     Running   0          4s
```

You can also edit the ReplicaSet and modify `spec.replicas` to scale.

***

## 14) Scale the ReplicaSet down to 2 pods (edit approach)

Edit the ReplicaSet:

```bash theme={null}
kubectl edit rs new-replica-set
```

Change `spec.replicas` to `2`:

```yaml theme={null}
spec:
  replicas: 2
  selector:
    matchLabels:
      name: busybox-pod
  template:
    metadata:
      labels:
        name: busybox-pod
    ...
```

Save the change. The ReplicaSet controller will terminate excess pods to match the desired replica count of 2.

***

That's it for this lab lesson.

Links and References

* [Kubernetes ReplicaSet documentation](https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/)
* [kubectl reference](https://kubernetes.io/docs/reference/kubectl/)
* [kubectl explain](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#explain)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/cka-certification-course-certified-kubernetes-administrator/module/c6d2ac7d-8192-4cff-aa54-e36d888c5bd9/lesson/b2fda7e9-2e8f-4532-8cc6-11a9d7d93ebd" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.