DEV Community

janak0ff
janak0ff

Posted on

Deploy ReplicaSet in Kubernetes Cluster

The Nautilus DevOps team is gearing up to deploy applications on a Kubernetes cluster for migration purposes. A team member has been tasked with creating a ReplicaSet outlined below:

  1. Create a ReplicaSet using nginx image with latest tag (ensure to specify as nginx:latest) and name it nginx-replicaset.
  2. Apply labels: app as nginx_apptype as front-end.
  3. Name the container nginx-container. Ensure the replica count is 4.

Solution

Step 1: Generate the ReplicaSet YAML

First, let's generate a base ReplicaSet manifest:

kubectl create replicaset nginx-replicaset \
  --image=nginx:latest \
  --dry-run=client -o yaml > nginx-replicaset.yaml
Enter fullscreen mode Exit fullscreen mode

Step 2: Edit the YAML to Add Requirements

Open the file and modify it according to the requirements:

nano nginx-replicaset.yaml
Enter fullscreen mode Exit fullscreen mode

Update the file with:

  • Replica count: 4
  • Labels: app: nginx_app, type: front-end
  • Container name: nginx-container

Here's the complete YAML:

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: nginx-replicaset
  labels:
    app: nginx_app
    type: front-end
spec:
  replicas: 4
  selector:
    matchLabels:
      app: nginx_app
      type: front-end
  template:
    metadata:
      labels:
        app: nginx_app
        type: front-end
    spec:
      containers:
      - name: nginx-container
        image: nginx:latest
        ports:
        - containerPort: 80
Enter fullscreen mode Exit fullscreen mode

Step 3: Apply the ReplicaSet

Create the ReplicaSet in your cluster:

kubectl apply -f nginx-replicaset.yaml
Enter fullscreen mode Exit fullscreen mode

Expected output:

replicaset.apps/nginx-replicaset created
Enter fullscreen mode Exit fullscreen mode

Step 4: Verify the ReplicaSet

Check that the ReplicaSet was created successfully:

kubectl get replicasets
Enter fullscreen mode Exit fullscreen mode

Expected output:

NAME                DESIRED   CURRENT   READY   AGE
nginx-replicaset    4         4         4       10s
Enter fullscreen mode Exit fullscreen mode

Step 5: Verify Pods

Check that 4 pods were created:

kubectl get pods
Enter fullscreen mode Exit fullscreen mode

Expected output:

NAME                      READY   STATUS    RESTARTS   AGE
nginx-replicaset-xxxxx    1/1     Running   0          15s
nginx-replicaset-yyyyy    1/1     Running   0          15s
nginx-replicaset-zzzzz    1/1     Running   0          15s
nginx-replicaset-wwwww    1/1     Running   0          15s
Enter fullscreen mode Exit fullscreen mode

Step 6: Verify Labels

Check that the labels are correctly applied:

kubectl get replicaset nginx-replicaset --show-labels
Enter fullscreen mode Exit fullscreen mode

Expected output:

NAME                DESIRED   CURRENT   READY   AGE   LABELS
nginx-replicaset    4         4         4       30s   app=nginx_app,type=front-end
Enter fullscreen mode Exit fullscreen mode

Step 7: Verify Pod Labels

Check that pods have the correct labels:

kubectl get pods --show-labels
Enter fullscreen mode Exit fullscreen mode

Expected output:

NAME                      READY   STATUS    RESTARTS   AGE   LABELS
nginx-replicaset-xxxxx    1/1     Running   0          20s   app=nginx_app,type=front-end
nginx-replicaset-yyyyy    1/1     Running   0          20s   app=nginx_app,type=front-end
nginx-replicaset-zzzzz    1/1     Running   0          20s   app=nginx_app,type=front-end
nginx-replicaset-wwwww    1/1     Running   0          20s   app=nginx_app,type=front-end
Enter fullscreen mode Exit fullscreen mode

Step 8: Detailed Verification

Get detailed information about the ReplicaSet:

kubectl describe replicaset nginx-replicaset
Enter fullscreen mode Exit fullscreen mode

Alternative Methods

Method 1: Using kubectl create Directly

Create the ReplicaSet with a single command:

kubectl create replicaset nginx-replicaset \
  --image=nginx:latest \
  --replicas=4 \
  --labels="app=nginx_app,type=front-end" \
  --dry-run=client -o yaml > nginx-replicaset.yaml
Enter fullscreen mode Exit fullscreen mode

Then apply it:

kubectl apply -f nginx-replicaset.yaml
Enter fullscreen mode Exit fullscreen mode

Method 2: Complete YAML from Scratch

Create a YAML file named nginx-replicaset.yaml with the complete specification:

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: nginx-replicaset
  labels:
    app: nginx_app
    type: front-end
spec:
  replicas: 4
  selector:
    matchLabels:
      app: nginx_app
      type: front-end
  template:
    metadata:
      labels:
        app: nginx_app
        type: front-end
    spec:
      containers:
      - name: nginx-container
        image: nginx:latest
        ports:
        - containerPort: 80
        resources:
          requests:
            memory: "64Mi"
            cpu: "100m"
          limits:
            memory: "128Mi"
            cpu: "200m"
Enter fullscreen mode Exit fullscreen mode

Apply it:

kubectl apply -f nginx-replicaset.yaml
Enter fullscreen mode Exit fullscreen mode

Method 3: Using kubectl run (Not Recommended for ReplicaSets)

kubectl run nginx-replicaset \
  --image=nginx:latest \
  --labels="app=nginx_app,type=front-end" \
  --port=80 \
  --replicas=4 \
  --restart=Always \
  --dry-run=client -o yaml > nginx-replicaset.yaml
Enter fullscreen mode Exit fullscreen mode

Complete Verification Commands

1. Check ReplicaSet Status

# Basic status
kubectl get replicaset nginx-replicaset

# Detailed with labels
kubectl get replicaset nginx-replicaset --show-labels

# Wide output
kubectl get replicaset nginx-replicaset -o wide

# Custom columns
kubectl get replicaset nginx-replicaset -o custom-columns=NAME:.metadata.name,DESIRED:.spec.replicas,READY:.status.readyReplicas,AGE:.metadata.creationTimestamp
Enter fullscreen mode Exit fullscreen mode

2. Check Pods

# List all pods
kubectl get pods

# Filter pods by label
kubectl get pods -l app=nginx_app

# Show pod labels
kubectl get pods --show-labels

# Get pod details
kubectl describe pods -l app=nginx_app
Enter fullscreen mode Exit fullscreen mode

3. Check ReplicaSet Details

# Describe ReplicaSet
kubectl describe replicaset nginx-replicaset

# Get YAML output
kubectl get replicaset nginx-replicaset -o yaml

# Get JSON output
kubectl get replicaset nginx-replicaset -o json
Enter fullscreen mode Exit fullscreen mode

4. Verify Image Version

# Check image of pods
kubectl get pods -l app=nginx_app -o jsonpath='{.items[*].spec.containers[0].image}'

# Check image via ReplicaSet
kubectl get replicaset nginx-replicaset -o jsonpath='{.spec.template.spec.containers[0].image}'
Enter fullscreen mode Exit fullscreen mode

5. Check Events

# Check events related to ReplicaSet
kubectl get events --field-selector involvedObject.name=nginx-replicaset

# Check events related to pods
kubectl get events --field-selector involvedObject.kind=Pod | grep nginx-replicaset
Enter fullscreen mode Exit fullscreen mode

Understanding ReplicaSets

What is a ReplicaSet?

A ReplicaSet ensures that a specified number of pod replicas are running at any given time. It replaces the older ReplicationController with more advanced label selectors.

┌─────────────────────────────────────────────┐
│            ReplicaSet                       │
│         (nginx-replicaset)                  │
│         Desired: 4 pods                     │
│         Labels: app=nginx_app              │
│                 type=front-end              │
└──────────────────┬──────────────────────────┘
                   │
        ┌──────────┼──────────┐
        │          │          │
        ▼          ▼          ▼
    ┌───────┐ ┌───────┐ ┌───────┐
    │Pod 1  │ │Pod 2  │ │Pod 3  │
    │Running│ │Running│ │Running│
    └───────┘ └───────┘ └───────┘
        │
        ▼
    ┌───────┐
    │Pod 4  │
    │Running│
    └───────┘
Enter fullscreen mode Exit fullscreen mode

ReplicaSet vs Deployment

Feature ReplicaSet Deployment
Purpose Maintain pod count Manage application lifecycle
Rolling Updates ❌ No ✅ Yes
Rollbacks ❌ No ✅ Yes
Scaling ✅ Yes ✅ Yes
Self-healing ✅ Yes ✅ Yes
Use Case When you need simple replication Most production applications

Why Use a ReplicaSet?

  1. High Availability: Ensures your application always has the desired number of replicas
  2. Self-Healing: Automatically replaces failed pods
  3. Scalability: Easy to scale up or down
  4. Load Distribution: Distributes traffic across multiple pods

Advanced Operations

1. Scaling the ReplicaSet

# Scale to 6 replicas
kubectl scale replicaset nginx-replicaset --replicas=6

# Verify
kubectl get replicaset nginx-replicaset

# Check pods
kubectl get pods -l app=nginx_app
Enter fullscreen mode Exit fullscreen mode

2. Update Image

# Update the ReplicaSet to use a different image
kubectl set image replicaset nginx-replicaset nginx-container=nginx:1.21

# Check the updated image
kubectl get replicaset nginx-replicaset -o jsonpath='{.spec.template.spec.containers[0].image}'
Enter fullscreen mode Exit fullscreen mode

3. Edit ReplicaSet

# Edit the ReplicaSet directly
kubectl edit replicaset nginx-replicaset

# After editing, the ReplicaSet will start new pods
Enter fullscreen mode Exit fullscreen mode

4. Delete ReplicaSet

# Delete the ReplicaSet (and its pods)
kubectl delete replicaset nginx-replicaset

# Delete using YAML
kubectl delete -f nginx-replicaset.yaml

# Delete only the ReplicaSet, not the pods
kubectl delete replicaset nginx-replicaset --cascade=false
Enter fullscreen mode Exit fullscreen mode

Troubleshooting

Issue 1: Pods Not Creating

Error: ReplicaSet shows 0 pods

Solutions:

# Check ReplicaSet events
kubectl describe replicaset nginx-replicaset

# Check if there's a label selector mismatch
kubectl get replicaset nginx-replicaset -o yaml | grep -A 5 selector
Enter fullscreen mode Exit fullscreen mode

Issue 2: ImagePullBackOff

Error: Pods stuck in ImagePullBackOff

Solutions:

# Check pod details
kubectl describe pod -l app=nginx_app

# Verify image name
kubectl get replicaset nginx-replicaset -o jsonpath='{.spec.template.spec.containers[0].image}'

# Update to correct image
kubectl set image replicaset nginx-replicaset nginx-container=nginx:latest
Enter fullscreen mode Exit fullscreen mode

Issue 3: Pods Not Running

Error: Pods in Pending state

Solutions:

# Check node resources
kubectl describe nodes

# Check pod events
kubectl describe pod -l app=nginx_app

# Check if there are resource constraints
kubectl get replicaset nginx-replicaset -o yaml | grep -A 5 resources
Enter fullscreen mode Exit fullscreen mode

Issue 4: Wrong Container Name

Error: Container name doesn't match

Solutions:

# Check container name
kubectl get replicaset nginx-replicaset -o jsonpath='{.spec.template.spec.containers[0].name}'

# Edit to correct name
kubectl edit replicaset nginx-replicaset
Enter fullscreen mode Exit fullscreen mode

Best Practices

✅ DO's

  1. Use Deployments Instead of ReplicaSets
   # Unless you have a specific reason to use ReplicaSet directly
   # Use Deployments for most use cases
Enter fullscreen mode Exit fullscreen mode
  1. Properly Define Selectors
   selector:
     matchLabels:
       app: nginx_app
       type: front-end
Enter fullscreen mode Exit fullscreen mode
  1. Set Resource Limits
   resources:
     requests:
       memory: "64Mi"
       cpu: "100m"
     limits:
       memory: "128Mi"
       cpu: "200m"
Enter fullscreen mode Exit fullscreen mode
  1. Add Health Checks
   livenessProbe:
     httpGet:
       path: /
       port: 80
     initialDelaySeconds: 30
     periodSeconds: 10
Enter fullscreen mode Exit fullscreen mode
  1. Use Meaningful Labels
   labels:
     app: nginx_app
     type: front-end
     environment: production
     version: "1.0"
Enter fullscreen mode Exit fullscreen mode
  1. Document Your ReplicaSet
   metadata:
     annotations:
       description: "Nginx web server for front-end applications"
       owner: "devops-team"
Enter fullscreen mode Exit fullscreen mode

❌ DON'Ts

  1. Don't Use ReplicaSets for Stateful Applications

    • Use StatefulSets instead
    • ReplicaSets are for stateless applications
  2. Don't Create ReplicaSets Without Selectors

    • Selectors are required
    • They determine which pods the ReplicaSet manages
  3. Don't Directly Modify Pods Managed by ReplicaSets

   # BAD - Pod will be recreated
   kubectl delete pod nginx-replicaset-xxxxx

   # GOOD - Scale the ReplicaSet
   kubectl scale replicaset nginx-replicaset --replicas=3
Enter fullscreen mode Exit fullscreen mode
  1. Don't Use :latest in Production
   # BAD - Unpredictable
   image: nginx:latest

   # GOOD - Specific version
   image: nginx:1.21.6
Enter fullscreen mode Exit fullscreen mode

Lab Completion Summary

✅ Task Requirements Checklist

  • [x] ReplicaSet created: nginx-replicaset
  • [x] Image: nginx:latest
  • [x] Labels: app: nginx_app, type: front-end
  • [x] Container name: nginx-container
  • [x] Replica count: 4
  • [x] All pods running: 4/4 ready

Final Verification Commands

echo "=== ReplicaSet Status ==="
kubectl get replicaset nginx-replicaset

echo -e "\n=== Pod Status ==="
kubectl get pods -l app=nginx_app

echo -e "\n=== Labels ==="
kubectl get replicaset nginx-replicaset --show-labels

echo -e "\n=== Container Image ==="
kubectl get replicaset nginx-replicaset -o jsonpath='{.spec.template.spec.containers[0].image}'

echo -e "\n\n=== Container Name ==="
kubectl get replicaset nginx-replicaset -o jsonpath='{.spec.template.spec.containers[0].name}'

echo -e "\n\n=== Replica Count ==="
kubectl get replicaset nginx-replicaset -o jsonpath='{.spec.replicas}'

echo -e "\n\n=== All Resources ==="
kubectl get all -l app=nginx_app
Enter fullscreen mode Exit fullscreen mode

Expected output:

=== ReplicaSet Status ===
NAME                DESIRED   CURRENT   READY   AGE
nginx-replicaset    4         4         4       2m

=== Pod Status ===
NAME                      READY   STATUS    RESTARTS   AGE
nginx-replicaset-xxxxx    1/1     Running   0          2m
nginx-replicaset-yyyyy    1/1     Running   0          2m
nginx-replicaset-zzzzz    1/1     Running   0          2m
nginx-replicaset-wwwww    1/1     Running   0          2m

=== Labels ===
NAME                DESIRED   CURRENT   READY   AGE   LABELS
nginx-replicaset    4         4         4       2m    app=nginx_app,type=front-end

=== Container Image ===
nginx:latest

=== Container Name ===
nginx-container

=== Replica Count ===
4
Enter fullscreen mode Exit fullscreen mode

Success! 🎉

Top comments (0)