Skip to content

📦 ReplicaSet Management

A ReplicaSet ensures that a specified number of identical Pods are running at all times. It replaces failed Pods and scales the number of replicas to match the desired state.


✅ When to Use a ReplicaSet

Use ReplicaSets when you need:

  • A fixed number of pod replicas
  • Automatic pod replacement if they fail

⚠️ In most cases, use a Deployment instead, which manages ReplicaSets and adds rollback, rollout, and upgrade strategies.


🔧 Create a ReplicaSet imperative

kubectl apply -f replicaset-definition.yaml

🔧 Create a ReplicaSet from YAML

kubectl apply -f replicaset-definition.yaml

Example YAML

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: replicaset-2
spec:
  replicas: 3
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp
        image: myimage

✅ Ensure:

  • selector.matchLabels matches template.metadata.labels

🔍 Inspect and Manage ReplicaSets

List all ReplicaSets

kubectl get rs

View details of a ReplicaSet

kubectl describe rs <replica-set-name>

Edit a ReplicaSet

kubectl edit rs <replica-set-name>

Delete a ReplicaSet

kubectl delete rs <replica-set-name>

Deleting a ReplicaSet also deletes its managed Pods (unless orphaned).


📈 Scale a ReplicaSet

Method 1: Using the scale command

kubectl scale rs replicaset-2 --replicas=5

Method 2: Edit directly

kubectl edit rs replicaset-2
# Change: replicas: 3 → 5

❌ Common ReplicaSet Issues

Label Mismatch (No Pods Created)

# Incorrect:
spec:
  selector:
    matchLabels:
      role: api
  template:
    metadata:
      labels:
        role: db  # ❌ mismatch
# Correct:
spec:
  selector:
    matchLabels:
      role: api
  template:
    metadata:
      labels:
        role: api  # ✅ match

Example fix

kubectl apply -f rs-fixed.yaml
kubectl get rs
kubectl get pods -l role=api

🔍 Filtering ReplicaSet Pods

Get Pods by label (managed by RS)

kubectl get pods -l app=myapp

View images used

kubectl get pods -o jsonpath="{.items[*].spec.containers[*].image}"

✅ Summary

  • ReplicaSet keeps a fixed number of Pods running
  • Defined by YAML with replicas, selector, and template
  • Must match selector.matchLabels with template.metadata.labels
  • Use kubectl scale or kubectl edit to adjust replica count
  • Prefer Deployments for rolling updates, rollbacks, and production usage