Deployments & ReplicaSets: Scaling and Updating Apps

7 min read

Deployments & ReplicaSets: Scaling and Updating Apps 🚀

Welcome back to our Kubernetes journey! Today, we're diving into the magic of keeping your applications running smoothly and updating them without your users even noticing. Imagine you're running a popular online game. You can't just turn it off to update it, right? Your players would be furious! This is where Deployments and ReplicaSets come in to save the day.


1. ReplicaSets: Ensuring High Availability and Desired State 🛡️

The Problem: Let's say you have an application running in a Pod. What happens if that Pod crashes? Your application goes down. 😱 That's a single point of failure. You could manually create another Pod, but who wants to be on call 24/7 to do that? We need an automated way to ensure a specific number of Pods are always running.

The Solution: ReplicaSets

A ReplicaSet is a Kubernetes object that ensures a specified number of pod "replicas" are running at any given time. Think of it as a vigilant supervisor for your Pods. If a Pod goes down, the ReplicaSet immediately creates a new one to take its place.

How it Works (Under the Hood):

A ReplicaSet uses a selector to identify which Pods it's responsible for managing. This selector is defined by labels. Any Pod with matching labels will be under the ReplicaSet's control. The replicas field specifies the desired number of Pods.

YAML Example:

Here’s a basic ReplicaSet definition:

yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: my-app-replicaset
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app-container
        image: nginx

Breakdown of the YAML:

  • apiVersion: apps/v1 and kind: ReplicaSet: This tells Kubernetes what kind of object we're creating.
  • metadata: Contains information about the ReplicaSet, like its name.
  • spec.replicas: 3: This is the magic number. We're telling the ReplicaSet we want three Pods running.
  • spec.selector.matchLabels: This is how the ReplicaSet knows which Pods to manage. It's looking for Pods with the label app: my-app.
  • spec.template: This is a blueprint for the Pods the ReplicaSet will create. It includes the Pod's metadata (with the all-important matching label) and spec (which defines the containers to run).

Industry Practice:

In the real world, you'll rarely create ReplicaSets directly. Why? Because a more powerful object, the Deployment, manages them for you. It's like having a manager for your supervisor.


2. Deployments: The Master Controller for Stateless Apps 🎮

The Problem: ReplicaSets are great for keeping a stable set of Pods running. But what about updates? If you want to update your application to a new version, you'd have to manually delete the old ReplicaSet and create a new one. This would cause downtime. We need a way to manage updates gracefully.

The Solution: Deployments

A Deployment is a higher-level Kubernetes object that manages ReplicaSets and provides declarative updates to Pods. With a Deployment, you simply declare the desired state, and the Deployment will take care of getting you there in a controlled way.

How it Works (Under the Hood):

When you create a Deployment, it creates a ReplicaSet in the background. When you want to update your application (e.g., change the container image), you update the Deployment's Pod template. The Deployment then creates a new ReplicaSet with the updated template and gradually scales it up while scaling down the old ReplicaSet. This is the magic of rolling updates!

YAML Example:

Here’s a basic Deployment definition. Notice how similar it is to the ReplicaSet!

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app-container
        image: nginx:1.14.2

Breakdown of the YAML:

The structure is almost identical to a ReplicaSet. The key difference is the kind: Deployment. This simple change gives us a whole new level of power, including updates and rollbacks.

Industry Practice:

For stateless applications (apps that don't need to store data on the server), Deployments are the standard and recommended way to run them in Kubernetes.

Interesting Fact: The concept of "desired state" is a core principle in Kubernetes. You tell Kubernetes what you want, and its controllers work tirelessly to make it a reality. It's like having a very obedient and powerful robot assistant.


3. Scaling Up and Down: Handling Traffic Spikes 🎢

The Problem: Your application is a huge success! But now, during peak hours, it's getting slow because of all the traffic. You need more Pods to handle the load, but you don't want to run extra Pods all the time because that costs money.

The Solution: Scaling Deployments

Deployments make it incredibly easy to scale the number of Pods up or down.

Manual Scaling:

You can quickly scale your application using the kubectl scale command.

Let's say you want to scale our my-app-deployment to 5 replicas:

bash
kubectl scale deployment my-app-deployment --replicas=5

And to scale it back down to 3:

bash
kubectl scale deployment my-app-deployment --replicas=3

Declarative Scaling:

The more "Kubernetes-native" way to scale is to update the replicas field in your Deployment's YAML file and apply the changes.

yaml
# my-app-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app-deployment
spec:
  replicas: 5 # Changed from 3 to 5
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app-container
        image: nginx:1.14.2

Then, apply the updated file:

bash
kubectl apply -f my-app-deployment.yaml

Under the Hood: When you scale a Deployment, you're actually changing the replicas field in its underlying ReplicaSet. The ReplicaSet's controller then notices the difference between the desired and actual number of Pods and takes action to create or delete Pods.

Industry Practice: For applications with predictable traffic patterns, manual scaling is common. For applications with unpredictable traffic, Kubernetes offers something called the Horizontal Pod Autoscaler (HPA), which can automatically scale your application based on CPU or memory usage. We'll cover that in a future guide!


4. Rolling Updates and Rollbacks: Zero-Downtime Releases 🔄

The Problem: You've developed a new version of your application with awesome new features. How do you deploy it without interrupting your users? A "big bang" release where you stop the old version and start the new one will cause downtime.

The Solution: Rolling Updates

This is where Deployments truly shine. By default, Deployments use a "rolling update" strategy. This means that when you update the Pod template (for example, by changing the container image), the Deployment gradually replaces the old Pods with new ones.

How a Rolling Update Works:

  1. You update the Pod template in your Deployment definition (e.g., change image: nginx:1.14.2 to image: nginx:1.15.0).
  2. You apply the updated YAML file using kubectl apply.
  3. The Deployment creates a new ReplicaSet with the new Pod template.
  4. It then scales up the new ReplicaSet by one Pod and scales down the old ReplicaSet by one Pod, while ensuring that the total number of available Pods doesn't drop below a certain threshold.
  5. This process continues until all the old Pods are replaced by new ones.
  6. Finally, the old ReplicaSet is scaled down to zero replicas.

This ensures that there are always Pods available to serve traffic, resulting in a zero-downtime deployment. 🥳

Performing a Rolling Update:

  1. Open your my-app-deployment.yaml file and change the image version:

    yaml
    # my-app-deployment.yaml
    ...
      containers:
      - name: my-app-container
        image: nginx:1.15.0 # Updated from 1.14.2
    ...
  2. Apply the change:

    bash
    kubectl apply -f my-app-deployment.yaml

You can monitor the status of the rollout with:

bash
kubectl rollout status deployment/my-app-deployment

Oops, Something Went Wrong! The Power of Rollbacks

Let's imagine the new version has a bug. 😱 No problem! Deployments keep a history of revisions, and you can easily roll back to a previous, stable version.

To see the revision history:

bash
kubectl rollout history deployment/my-app-deployment

To roll back to the previous version:

bash
kubectl rollout undo deployment/my-app-deployment

This will trigger another rolling update, but this time it will replace the new Pods with the old, stable ones.

Industry Practice: Rolling updates are the go-to strategy for deploying stateless applications in Kubernetes. For more complex deployment scenarios, such as canary releases or blue-green deployments, more advanced techniques and tools can be used, but the rolling update is your everyday workhorse.


Extra Reading & References 📚

Challenge

You are a DevOps engineer responsible for managing a web application. A new version is ready for release, and you need to scale up to meet anticipated traffic. Modify the provided Kubernetes Deployment manifest to perform the following actions:

  1. Scale Out: Increase the number of replicas from 2 to 5 to enhance availability and handle increased load.
  2. Update Image: A new, more secure version of the application is available. Update the container image from webapp:1.0 to webapp:1.2.
  3. Refine Rollout Strategy: Configure a more controlled rolling update. Set maxUnavailable to 1 pod and maxSurge to 25%.
  4. Add Environment Label: Add a new label env: production to the Pod template's metadata. Crucially, you must also update the Deployment's spec.selector.matchLabels to include this new label, otherwise, the Deployment will lose control over its Pods.

Expected result

A single, valid Kubernetes Deployment YAML manifest. The final configuration should have the replicas field set to 5. The container's image should be webapp:1.2. A strategy block must be present under spec defining a rollingUpdate with maxUnavailable as 1 and maxSurge as 25%. Finally, both the spec.selector.matchLabels and spec.template.metadata.labels sections must contain the env: production label in addition to the original app: webapp label.

yaml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.