Chapter 3.5 - ReplicaSets
Learning Objectives
By the end of this chapter, you will be able to:
- Understand the role of ReplicaSets
- Create and manage ReplicaSets
- Understand how ReplicaSets maintain the number of replicas
- Use ReplicaSets with Deployments
What is a ReplicaSet?
A ReplicaSet maintains a stable number of running Pod replicas. It guarantees that a specified number of identical Pods is always available.
Why ReplicaSets?
Self-Healing
If a Pod crashes, the ReplicaSet automatically creates a new Pod:
Scaling
You can easily increase or decrease the number of replicas.
YAML Declaration
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: web-replicaset
labels:
app: web
tier: frontend
spec:
replicas: 3
selector:
matchLabels:
app: web
tier: frontend
template:
metadata:
labels:
app: web
tier: frontend
spec:
containers:
- name: nginx
image: nginx:1.20
ports:
- containerPort: 80
Important Sections
- replicas: Desired number of Pods
- selector: How to identify Pods to manage
- template: Template for creating new Pods
Selector and Labels
Important: The labels in selector.matchLabels must match the labels in template.metadata.labels.
Managing ReplicaSets
Create a ReplicaSet
# From a YAML file
kubectl apply -f replicaset.yaml
# Create and view the YAML
kubectl create replicaset web-rs --image=nginx:1.20 --replicas=3 --dry-run=client -o yaml
Scaling
# Change the number of replicas
kubectl scale replicaset web-replicaset --replicas=5
# Or edit directly
kubectl edit replicaset web-replicaset
Delete
# Delete the ReplicaSet (Pods too)
kubectl delete replicaset web-replicaset
# Delete only the ReplicaSet (keep Pods)
kubectl delete replicaset web-replicaset --cascade=orphan
ReplicaSets vs Deployments
ReplicaSets (Low Level)
- Directly manage Pods
- No version management
- No rolling updates
Deployments (High Level)
- Manage ReplicaSets
- Version management
- Rolling updates and rollbacks
- Recommended for most use cases
Summary
In this chapter, you learned:
ReplicaSet: Maintains a stable number of identical Pods
Self-healing: Automatically creates new Pods when needed
Scaling: Easily adjustable
Selector: Identifies Pods to manage
Deployments: Use ReplicaSets with advanced features
Next Steps
Now that you understand ReplicaSets:
Chapter 3.6: Deployments - Advanced Management
Lab 3.2: Deploying with ReplicaSets
Chapter created: December 2024