# Deployment, ReplicaSet, & ReplicationController

### **What is a Deployment?**

A **Deployment** in Kubernetes is the most commonly used controller for managing application workloads.\
It provides a **declarative way** to define what your application should look like how many replicas should run, what image to use, and how updates or rollbacks should occur.

You don’t create Pods directly in production. Instead, you create a **Deployment** that manages **ReplicaSets**, which in turn manage the Pods.\
This layered design allows Kubernetes to perform **rolling updates, automatic scaling, and versioned rollbacks** without downtime.

At a high level:

```
Deployment → manages ReplicaSets → manages Pods
```

#### **Key Responsibilities of a Deployment**

* Ensures a specified number of Pod replicas are always running.
* Handles **zero-downtime rolling updates** when you deploy new versions.
* Supports **rollbacks** if something goes wrong.
* Manages **ReplicaSets** automatically (you never have to create them yourself).
* Makes scaling (up/down) straightforward.

#### **Deployment YAML Example**

```yaml
apiVersion: apps/v1           # API group for Deployments
kind: Deployment              # Resource type
metadata:
  name: nginx-deployment      # Deployment name
  labels:
    app: nginx
spec:
  replicas: 3                 # Desired number of Pods
  selector:                   # Defines which Pods this Deployment manages
    matchLabels:
      app: nginx
  strategy:                   # Defines how updates are rolled out
    type: RollingUpdate       # RollingUpdate (default) or Recreate
    rollingUpdate:
      maxUnavailable: 1       # How many Pods can be unavailable during update
      maxSurge: 1             # How many extra Pods can be created temporarily
  template:                   # Pod template used to create Pods
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.24     # Container image
        ports:
        - containerPort: 80
        resources:
          requests:
            cpu: "100m"       # Minimum guaranteed CPU
            memory: "128Mi"   # Minimum guaranteed memory
          limits:
            cpu: "500m"       # Max CPU allowed
            memory: "256Mi"   # Max memory allowed
```

#### **Breaking Down the YAML**

* **apiVersion: apps/v1** → Deployments are part of the `apps` API group.
* **kind: Deployment** → Tells Kubernetes this is a Deployment resource.
* **metadata:** Defines identifying information, name, labels, etc.
* **spec.replicas:** Desired number of Pods you want to run.
* **spec.selector:** Specifies which Pods belong to this Deployment (via labels).
* **spec.strategy:** How updates are performed (rolling or recreate).
* **spec.template:** Describes the Pod that should be created and managed by this Deployment.

The **template** field inside the Deployment is identical to a Pod definition, it defines container image, ports, probes, resources, etc.

#### **Creating and Viewing a Deployment**

```bash
kubectl apply -f nginx-deployment.yaml
kubectl get deployments
kubectl get pods
kubectl get rs   # Shows the ReplicaSet created by the Deployment
```

You’ll see that Kubernetes automatically created:

* A **Deployment**
* A **ReplicaSet**
* Multiple **Pods**

#### **Updating a Deployment**

If you change the image or configuration in the YAML and reapply it, Kubernetes will:

1. Create a **new ReplicaSet** for the updated Pods.
2. Gradually spin up new Pods while scaling down the old ones (rolling update).
3. Maintain the specified number of replicas during the transition.

Example:

```bash
kubectl set image deployment/nginx-deployment nginx=nginx:1.25
kubectl rollout status deployment/nginx-deployment
```

Rollback if something breaks:

```bash
kubectl rollout undo deployment/nginx-deployment
```

#### **Scaling a Deployment**

You can scale up or down manually:

```bash
kubectl scale deployment nginx-deployment --replicas=5
```

or modify `spec.replicas` and reapply the YAML.

#### **Deleting a Deployment**

```bash
kubectl delete deployment nginx-deployment
```

This automatically deletes its ReplicaSets and Pods.

#### **Why Use Deployments**

* **Self-healing:** Automatically recreates failed Pods.
* **Declarative updates:** You define *what* you want, Kubernetes figures out *how* to achieve it.
* **Rollbacks:** Keeps history of revisions for safe rollback.
* **Automation:** You don’t manage ReplicaSets or Pods manually the Deployment does it.

Deployments are the **industry standard** way to manage stateless workloads in Kubernetes.

### **What is a ReplicaSet?**

A **ReplicaSet (RS)** is the **middle layer** between Deployments and Pods.\
Its core responsibility is simple - ensure a specific number of identical Pods are always running.

ReplicaSets were introduced to replace **ReplicationControllers**, adding better label selectors and integration with Deployments.

When you create a Deployment, Kubernetes **automatically creates a ReplicaSet** behind the scenes.

#### **How ReplicaSets Work**

* A ReplicaSet continuously monitors Pods matching its label selector.
* If a Pod dies or is deleted, it creates a new one.
* If there are too many Pods (e.g., created manually), it deletes the extras.
* Each ReplicaSet corresponds to **a specific version of your Pod template** (useful for rollbacks).

#### **ReplicaSet YAML Example**

```yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: nginx-rs
  labels:
    app: nginx
spec:
  replicas: 3                # Desired number of Pods
  selector:                  # Which Pods this RS should manage
    matchLabels:
      app: nginx
  template:                  # Pod template (same as in Deployment)
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.24
        ports:
        - containerPort: 80
```

#### **Breaking Down the YAML**

* **replicas:** Number of Pods the ReplicaSet should maintain.
* **selector.matchLabels:** Identifies which Pods are managed by this RS.
* **template:** Defines the Pod structure (metadata + spec).\
  If no existing Pods match the selector, it creates new ones.

#### **Practical Example**

```bash
kubectl apply -f nginx-rs.yaml
kubectl get rs
kubectl get pods
```

Delete one of the Pods and watch how it gets recreated:

```bash
kubectl delete pod <pod-name>
kubectl get pods
```

The RS detects the missing Pod and automatically spins up a replacement.

#### **Set-Based Label Selectors**

ReplicaSets support advanced label matching beyond simple equality.

Example:

```yaml
selector:
  matchExpressions:
  - key: tier
    operator: In
    values:
    - frontend
    - api
```

This matches Pods that have either `tier=frontend` **or** `tier=api`.

#### **When to Use ReplicaSet Directly**

In practice, you rarely use ReplicaSets directly they are almost always managed by Deployments.\
However, they’re still useful for advanced, static workloads where you want fine-grained control without automatic rollouts.

### **What is a ReplicationController?**

A **ReplicationController (RC)** is the **oldest Kubernetes controller** that ensures a specified number of identical Pods are running at all times.

It was introduced in the earliest versions of Kubernetes and provided the foundation for ReplicaSets.\
Although it still exists for backward compatibility, it’s considered **deprecated** ReplicaSets and Deployments have fully replaced it.

#### **ReplicationController Responsibilities**

* Maintain a specified number of Pod replicas.
* Replace failed or deleted Pods.
* Scale the number of Pods manually.

It lacks advanced features like set-based selectors, rolling updates, or rollbacks.

#### **ReplicationController YAML Example**

```yaml
apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx-rc
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.24
        ports:
        - containerPort: 80
```

#### **Explanation**

* **replicas:** Desired number of Pods.
* **selector:** Equality-based label matching only.
* **template:** The Pod spec to use for new Pods.

#### **Commands**

```bash
kubectl apply -f nginx-rc.yaml
kubectl get rc
kubectl get pods
```

You’ll see 3 Pods running.\
Delete one:

```bash
kubectl delete pod <pod-name>
```

A new one will appear immediately that’s the RC maintaining the desired state.

### **How These Three Relate ?**

Here’s the relationship between them:

```
Deployment
  └── ReplicaSet (automatically created & managed)
        └── Pods (created and monitored)
```

And historically:

```
ReplicationController → ReplicaSet → Deployment
```

| Feature         | **ReplicationController** | **ReplicaSet**                | **Deployment**                        |
| --------------- | ------------------------- | ----------------------------- | ------------------------------------- |
| Purpose         | Maintain Pod count        | Maintain Pod count (enhanced) | Manage ReplicaSets and handle updates |
| Selector type   | Equality-based            | Set-based                     | Delegated to RS                       |
| Rolling updates | Manual                    | Manual                        | Automated                             |
| Rollbacks       | ❌                         | ❌                             | ✅                                     |
| Current status  | Legacy                    | Used by Deployments           | Recommended                           |

When you apply a Deployment, you’re really using all three ideas, just abstracted under one powerful controller.\
Understanding this hierarchy is key to troubleshooting, scaling, and designing resilient workloads in Kubernetes.
