Kubernetes ReplicaSets Practical: Hands-On Tutorial with YAML & kubectl Commands

Practical Kubernetes ReplicaSets tutorial with step-by-step examples, YAML configuration, kubectl commands, and self-healing demonstrations.

ReplicaSet Example

Download the YAML configuration file for the ReplicaSet example

Download rs-example.yaml

Create the ReplicaSet

kubectl apply -f rs-example.yaml

Applies the configuration from the YAML file to create the ReplicaSet with 3 replicas.

Get the Pods List

kubectl get pods -o wide

Lists all pods with additional details including node assignment.

Get the ReplicaSet Name

kubectl get rs

Lists all ReplicaSets in the current namespace.

Describe the ReplicaSet

kubectl describe rs rs-example

Shows detailed information about the ReplicaSet including events and pod status.

Cleanup

kubectl delete -f rs-example.yaml

Deletes all resources defined in the YAML configuration file.

YAML Configuration File

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: rs-example
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
      type: front-end
  template: 
    metadata:
      labels:
        app: nginx
        type: front-end
    spec:
      containers:
      - name: nginx
        image: nginx:alpine
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
          limits:
            cpu: 250m
            memory: 256Mi 
        ports:
        - containerPort: 80

YAML Configuration Explanation:

ReplicaSet Structure:

  • apiVersion: apps/v1 → Specifies the Kubernetes API version for ReplicaSet
  • kind: ReplicaSet → Defines this as a ReplicaSet resource
  • metadata.name: rs-example → Names the ReplicaSet "rs-example"

ReplicaSet Spec:

  • replicas: 3 → Maintains 3 identical pod instances
  • selector.matchLabels → Defines which pods this ReplicaSet manages
  • app: nginx, type: front-end → Labels that pods must have to be managed

Pod Template:

  • template.metadata.labels → Labels applied to created pods
  • template.spec → Pod specification for the containers
  • containers.name: nginx → Names the container "nginx"
  • image: nginx:alpine → Uses the lightweight Alpine-based Nginx image

Container Resources:

  • resources.requests → Minimum resources required
  • cpu: 100m → Requests 0.1 CPU cores
  • memory: 128Mi → Requests 128 MB of memory
  • resources.limits → Maximum resources allowed
  • cpu: 250m → Limits to 0.25 CPU cores
  • memory: 256Mi → Limits to 256 MB of memory

Container Port:

  • containerPort: 80 → Exposes port 80 for web traffic
  • This is informational and doesn't actually publish the port

How It Works:

The ReplicaSet ensures that exactly 3 pod replicas are running at all times. If a pod fails or is deleted, the ReplicaSet automatically creates a new one to maintain the desired count. The selector ensures that only pods with the labels "app: nginx" and "type: front-end" are managed by this ReplicaSet.