Skip to main content

Lab 3.2 - Deploying with ReplicaSets

Objectives

By the end of this lab, you will be able to:

  • Create and manage ReplicaSets
  • Understand self-healing
  • Scale ReplicaSets
  • Observe ReplicaSet behavior

Exercise 1: Create a ReplicaSet

Step 1: Create the YAML file

Create replicaset.yaml:

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

Step 2: Apply

kubectl apply -f replicaset.yaml

Step 3: Verify

# View the ReplicaSet
kubectl get replicaset

# View the created Pods
kubectl get pods -l app=web

Exercise 2: Self-Healing

Step 1: Delete a Pod

# Delete a Pod
kubectl delete pod <pod-name>

# Observe immediately
kubectl get pods -l app=web -w

Question: What happens? A new Pod is automatically created.

Step 2: Check the ReplicaSet

kubectl describe replicaset web-replicaset

Exercise 3: Scaling

Step 1: Increase replicas

# Scale to 5 replicas
kubectl scale replicaset web-replicaset --replicas=5

# Verify
kubectl get pods -l app=web

Step 2: Decrease replicas

# Scale to 2 replicas
kubectl scale replicaset web-replicaset --replicas=2

# Observe the deletion
kubectl get pods -l app=web -w

Exercise 4: Modify the Template

Step 1: Edit the ReplicaSet

kubectl edit replicaset web-replicaset

Change the image from nginx:1.20 to nginx:1.21.

Question: What happens? Existing Pods do not change. Why?

Step 2: Delete the Pods

# Delete all Pods
kubectl delete pods -l app=web

# Observe the recreation
kubectl get pods -l app=web

The new Pods use the new image.


Cleanup

kubectl delete replicaset web-replicaset

Reflection Questions

  1. Why does the ReplicaSet not update existing Pods?
  2. How does the ReplicaSet maintain the number of replicas?
  3. What is the difference between a ReplicaSet and a Deployment?

Next Steps

Lab 3.3: Deployments and Rolling Updates
Chapter 3.6: Deployments


Lab created: December 2024