Ravindra BagaleCourses & study guides मराठी

Chapter 15: Kubernetes Introduction

DevOps

15.7 Rolling update and rollback (light)

Why: the problem

Suppose we are on the Paytm team and version 1.1 of the badge API is ready. We cannot stop the app to update it, because users pay all day. A rolling update replaces Pods a few at a time. Old Pods keep serving until new ones are Ready. If 1.1 is bad, one command takes us back to 1.0.

What we will build

You will roll the badge API from 1.0 to 1.1, watch Pods change, then push a broken tag and roll back with rollout undo. Same steps for all three stacks.

What: every term in plain English

  • Rolling update — Replacing old Pods with new ones step by step, with no downtime.
  • maxSurge — How many extra Pods may exist during the update.
  • maxUnavailable — How many Pods may be down during the update.
  • Revision — A saved version of the Deployment template.
  • rollout status — Waits and reports update progress.
  • rollout undo — Goes back to the previous revision.
Build and load 1.1 Update the image Watch the rollout See the history Push a broken tag See old Pods still serving Roll back
Rolling update: new Pod Ready, then old Pod removed

How: step by step

  1. Build and load 1.1

    docker build -t badge-node:1.1 .
    kind load docker-image badge-node:1.1 --name badge-api
    

    What it does: Makes the new version available in kind.

    Output

    Image: "badge-node:1.1" ... loaded
    
  2. Update the image

    kubectl set image deploy/badge-node api=badge-node:1.1
    

    What it does: Changes the Pod template, which starts a rollout.

    Output

    deployment.apps/badge-node image updated
    
  3. Watch the rollout

    kubectl rollout status deploy/badge-node
    

    What it does: Waits until all new Pods are Ready.

    Output

    Waiting for deployment "badge-node" rollout to finish: 1 of 2 updated replicas are available...
    deployment "badge-node" successfully rolled out
    
  4. See the history

    kubectl rollout history deploy/badge-node
    

    What it does: Each change is a revision.

    Output

    REVISION  CHANGE-CAUSE
    1         <none>
    2         <none>
    
  5. Push a broken tag

    kubectl set image deploy/badge-node api=badge-node:9.9
    

    What it does: A tag that does not exist.

    Output

    deployment.apps/badge-node image updated
    
  6. See old Pods still serving

    kubectl get pods
    

    What it does: New Pod fails, old ones stay Running. Users are safe.

    Output

    badge-node-7c9d8f6b4-x2k8p   0/1   ErrImageNeverPull   0   20s
    badge-node-5b8c9d7f6-k3j9q   1/1   Running             0   3m
    
  7. Roll back

    kubectl rollout undo deploy/badge-node
    kubectl rollout status deploy/badge-node
    

    What it does: Returns to the last good revision.

    Output

    deployment.apps/badge-node rolled back
    deployment "badge-node" successfully rolled out
    

Example 1: Node

Stack. Node.js 20, Express, kind

Goal. Node.js: rolling update of badge-node with a safe strategy (one extra Pod, zero down).

server.js

// server.js - badge API (Node.js + Express)
const express = require("express");
const os = require("os");
const app = express();
app.get("/health", (req, res) => res.json({ status: "ok" }));
app.get("/badge/:user", (req, res) => {
  const user = req.params.user;
  if (!/^[a-z0-9_]{3,30}$/.test(user)) return res.status(400).json({ error: "invalid username" });
  res.json({ user, badge: "verified-learner", pod: os.hostname(), version: process.env.APP_VERSION || "1.0" });
});
app.listen(process.env.PORT || 3000, () => console.log("badge-node listening on 3000"));

Dockerfile

# Dockerfile - Node badge API
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY server.js .
USER node
EXPOSE 3000
CMD ["node", "server.js"]

k8s/badge-node.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: badge-node
  namespace: badge-api
  labels: { app: badge-node }
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate: { maxSurge: 1, maxUnavailable: 0 }
  selector:
    matchLabels: { app: badge-node }
  template:
    metadata:
      labels: { app: badge-node }
    spec:
      containers:
        - name: api
          image: badge-node:1.0
          ports:
            - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: badge-node
  namespace: badge-api
spec:
  type: ClusterIP
  selector: { app: badge-node }
  ports:
    - port: 80
      targetPort: 3000

What each line does

  • kind: Deployment — Tells Kubernetes: keep this many copies of the Pod running all the time.
  • replicas: 2 — Two Pods. If one dies, Kubernetes makes a new one.
  • selector.matchLabels — The Deployment owns Pods that carry this label.
  • image: ...:1.0 — A fixed tag. Never use latest, because you cannot tell what is running.
  • kind: Service / type: ClusterIP — One stable name and IP inside the cluster in front of all matching Pods.
  • port: 80 / targetPort — Callers use port 80. The Service sends traffic to the app port inside the Pod.
  • maxSurge: 1, maxUnavailable: 0 — Add one new Pod, wait until Ready, then remove one old Pod. Never fewer than 3 serving.

Green output

$ kubectl -n badge-api get pods -l app=badge-node
NAME                          READY   STATUS    RESTARTS   AGE
badge-node-6d9f7c8b5-4kq2x     1/1     Running   0          40s
badge-node-6d9f7c8b5-r7m9t     1/1     Running   0          40s
$ curl -s localhost:8080/badge/ravi
{"user":"ravi","badge":"verified-learner","pod":"badge-node-6d9f7c8b5-4kq2x","version":"1.0"}

Expected result. curl shows version 1.1 for Node.js after the rollout, and 1.0 again after undo.

Example 2: Python: rolling update of badge-py with a safe strategy (one extra Pod, zero down)

Stack. Python 3.12, Flask, gunicorn, kind

Goal. Python: rolling update of badge-py with a safe strategy (one extra Pod, zero down).

app.py

# app.py - badge API (Python + Flask)
import os, re, socket
from flask import Flask, jsonify
app = Flask(__name__)

@app.get("/health")
def health():
    return jsonify(status="ok")

@app.get("/badge/<user>")
def badge(user):
    if not re.fullmatch(r"[a-z0-9_]{3,30}", user):
        return jsonify(error="invalid username"), 400
    return jsonify(user=user, badge="verified-learner", pod=socket.gethostname(),
                   version=os.environ.get("APP_VERSION", "1.0"))

Dockerfile

# Dockerfile - Python badge API
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt   # flask, gunicorn
COPY app.py .
RUN useradd -u 10001 app
USER 10001
EXPOSE 5000
CMD ["gunicorn", "-b", "0.0.0.0:5000", "app:app"]

k8s/badge-py.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: badge-py
  namespace: badge-api
  labels: { app: badge-py }
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate: { maxSurge: 1, maxUnavailable: 0 }
  selector:
    matchLabels: { app: badge-py }
  template:
    metadata:
      labels: { app: badge-py }
    spec:
      containers:
        - name: api
          image: badge-py:1.0
          ports:
            - containerPort: 5000
---
apiVersion: v1
kind: Service
metadata:
  name: badge-py
  namespace: badge-api
spec:
  type: ClusterIP
  selector: { app: badge-py }
  ports:
    - port: 80
      targetPort: 5000

What each line does

  • kind: Deployment — Tells Kubernetes: keep this many copies of the Pod running all the time.
  • replicas: 2 — Two Pods. If one dies, Kubernetes makes a new one.
  • selector.matchLabels — The Deployment owns Pods that carry this label.
  • image: ...:1.0 — A fixed tag. Never use latest, because you cannot tell what is running.
  • kind: Service / type: ClusterIP — One stable name and IP inside the cluster in front of all matching Pods.
  • port: 80 / targetPort — Callers use port 80. The Service sends traffic to the app port inside the Pod.
  • maxSurge: 1, maxUnavailable: 0 — Add one new Pod, wait until Ready, then remove one old Pod. Never fewer than 3 serving.

Green output

$ kubectl -n badge-api get pods -l app=badge-py
NAME                          READY   STATUS    RESTARTS   AGE
badge-py-6d9f7c8b5-4kq2x     1/1     Running   0          40s
badge-py-6d9f7c8b5-r7m9t     1/1     Running   0          40s
$ curl -s localhost:8080/badge/ravi
{"user":"ravi","badge":"verified-learner","pod":"badge-py-6d9f7c8b5-4kq2x","version":"1.0"}

Expected result. curl shows version 1.1 for Python after the rollout, and 1.0 again after undo.

Example 3: Java: rolling update of badge-java with a safe strategy (one extra Pod, zero down)

Stack. Java 21, Spring Boot, kind

Goal. Java: rolling update of badge-java with a safe strategy (one extra Pod, zero down).

BadgeController.java

// src/main/java/com/shipit/BadgeController.java - badge API (Java + Spring Boot)
package com.shipit;
import org.springframework.web.bind.annotation.*;
import java.net.InetAddress;
import java.util.Map;

@RestController
public class BadgeController {
  @GetMapping("/health")
  public Map<String, String> health() { return Map.of("status", "ok"); }

  @GetMapping("/badge/{user}")
  public Map<String, String> badge(@PathVariable String user) throws Exception {
    if (!user.matches("[a-z0-9_]{3,30}")) throw new IllegalArgumentException("invalid username");
    String v = System.getenv().getOrDefault("APP_VERSION", "1.0");
    return Map.of("user", user, "badge", "verified-learner",
                  "pod", InetAddress.getLocalHost().getHostName(), "version", v);
  }
}

Dockerfile

# Dockerfile - Java badge API (two stages: build, then run)
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /src
COPY pom.xml .
COPY src ./src
RUN mvn -B -q package -DskipTests

FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=build /src/target/badge-api.jar app.jar
RUN useradd -u 10001 app
USER 10001
EXPOSE 8080
CMD ["java", "-jar", "app.jar"]

k8s/badge-java.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: badge-java
  namespace: badge-api
  labels: { app: badge-java }
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate: { maxSurge: 1, maxUnavailable: 0 }
  selector:
    matchLabels: { app: badge-java }
  template:
    metadata:
      labels: { app: badge-java }
    spec:
      containers:
        - name: api
          image: badge-java:1.0
          ports:
            - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: badge-java
  namespace: badge-api
spec:
  type: ClusterIP
  selector: { app: badge-java }
  ports:
    - port: 80
      targetPort: 8080

What each line does

  • kind: Deployment — Tells Kubernetes: keep this many copies of the Pod running all the time.
  • replicas: 2 — Two Pods. If one dies, Kubernetes makes a new one.
  • selector.matchLabels — The Deployment owns Pods that carry this label.
  • image: ...:1.0 — A fixed tag. Never use latest, because you cannot tell what is running.
  • kind: Service / type: ClusterIP — One stable name and IP inside the cluster in front of all matching Pods.
  • port: 80 / targetPort — Callers use port 80. The Service sends traffic to the app port inside the Pod.
  • maxSurge: 1, maxUnavailable: 0 — Add one new Pod, wait until Ready, then remove one old Pod. Never fewer than 3 serving.

Green output

$ kubectl -n badge-api get pods -l app=badge-java
NAME                          READY   STATUS    RESTARTS   AGE
badge-java-6d9f7c8b5-4kq2x     1/1     Running   0          40s
badge-java-6d9f7c8b5-r7m9t     1/1     Running   0          40s
$ curl -s localhost:8080/badge/ravi
{"user":"ravi","badge":"verified-learner","pod":"badge-java-6d9f7c8b5-4kq2x","version":"1.0"}

Expected result. curl shows version 1.1 for Java after the rollout, and 1.0 again after undo.

Verify: did it work?

  1. List everything in the namespace

    kubectl -n badge-api get all
    

    What it does: Shows Deployments, ReplicaSets, Pods and Services together.

    Output

    NAME                              READY   STATUS    RESTARTS   AGE
    pod/badge-node-6d9f7c8b5-4kq2x     1/1     Running   0          2m
    
    NAME                 TYPE        CLUSTER-IP     PORT(S)
    service/badge-node   ClusterIP   10.96.41.12    80/TCP
    
  2. Check that the Service found the Pods

    kubectl -n badge-api get endpoints badge-node
    

    What it does: Endpoints are the Pod IPs behind the Service. Empty means the labels do not match.

    Output

    NAME         ENDPOINTS                         AGE
    badge-node   10.244.0.5:3000,10.244.0.6:3000   2m
    
  3. Call the app through the Service

    kubectl -n badge-api port-forward svc/badge-node 8080:80 &
    curl -s localhost:8080/health
    

    What it does: Opens a tunnel from your laptop to the Service, then calls it.

    Output

    Forwarding from 127.0.0.1:8080 -> 3000
    {"status":"ok"}
    

When it is red 1

error: deployment "badge-node" exceeded its progress deadline

Cause. New Pods never became Ready in time (default 10 minutes).

Fix, step by step

  1. Run kubectl describe deploy badge-node and kubectl get pods.
  2. Fix the image or probe.
  3. Run kubectl rollout undo deploy/badge-node.

When it is red 2

NAME                          READY   STATUS             RESTARTS   AGE
badge-node-7c9d8f6b4-x2k8p    0/1     ImagePullBackOff   0          1m

Cause. The node cannot find the image. In kind, images on your laptop are not inside the cluster until you load them.

Fix, step by step

  1. Run kubectl describe pod and read the Events at the bottom.
  2. Check the tag in the YAML matches docker images.
  3. Run kind load docker-image badge-node:1.0 --name badge-api.
  4. Run kubectl rollout restart deployment/badge-node -n badge-api.

When it is red 3

NAME                          READY   STATUS             RESTARTS      AGE
badge-py-5f6c7d9b8-q8w2e      0/1     CrashLoopBackOff   4 (30s ago)   3m

Cause. The container starts and then exits again and again. Usually a code error, a missing package or a wrong command.

Fix, step by step

  1. Run kubectl logs --previous to see the last crash.
  2. Fix the code or the CMD in the Dockerfile.
  3. Build a new tag such as 1.1, load it, update the YAML and apply.

Cleanup

  1. Stop the port-forward

    kill %1
    

    What it does: Ends the background tunnel.

    Output

    [1]+  Terminated   kubectl port-forward svc/badge-node 8080:80
    
  2. Delete the lesson objects

    kubectl delete -f k8s/
    

    What it does: Removes what you applied. The cluster stays for the next lesson.

    Output

    deployment.apps "badge-node" deleted
    service "badge-node" deleted
    
  3. Delete the cluster at the end of the day

    kind delete cluster --name badge-api
    

    What it does: Removes the kind node container and frees memory.

    Output

    Deleting cluster "badge-api" ...
    Deleted nodes: ["badge-api-control-plane"]
    

Practice tasks

Easy Read the history

Why: Know what changed.

What to do: Run rollout history after two updates.

How:
  1. kubectl rollout history deploy/badge-node

Check: You see 2 or more revisions.

Medium Record the cause

Why: Revisions need a reason.

What to do: Add an annotation kubernetes.io/change-cause.

How:
  1. kubectl annotate deploy/badge-node kubernetes.io/change-cause="v1.1 new badge"

Check: History shows your text.

Hard Undo to a revision

Why: Jump back further.

What to do: Use --to-revision.

How:
  1. kubectl rollout undo deploy/badge-node --to-revision=1

Check: Version 1.0 answers.

Easy Say rolling updates in two lines

Why: If you can say it simply, you understand it.

What to do: Write two short lines about rolling updates for a fresher.

How:
  1. Write the problem it solves.
  2. Write the one command or field you use.

Check: A friend who never used Kubernetes understands your lines.

Easy Rebuild the kind cluster from zero

Why: Labs break. Starting fresh must feel easy.

What to do: Delete and create the badge-api kind cluster again.

How:
  1. kind delete cluster --name badge-api
  2. kind create cluster --name badge-api
  3. kubectl get nodes

Check: The node shows Ready in under two minutes.

Medium Do it for the second stack

Why: The same Kubernetes idea works for every language.

What to do: Repeat this lesson with the Python app if you used Node, or Java if you used Python.

How:
  1. Build the image with a 1.0 tag.
  2. kind load docker-image the image.
  3. Apply the YAML and curl it.

Check: curl returns JSON from the second stack.

Medium Break it and read describe

Why: Real work is mostly reading errors.

What to do: Put a wrong image tag in the YAML and apply it.

How:
  1. Change the tag to 9.9.
  2. kubectl apply -f the file.
  3. kubectl describe pod on the new Pod and read Events.

Check: You can point to the exact Events line that names the problem.

Medium Write the cleanup in one go

Why: Old labs fill the laptop disk.

What to do: Write the commands that remove everything this lesson made.

How:
  1. kubectl delete -f k8s/
  2. kubectl get all -n badge-api
  3. docker image prune

Check: kubectl get all -n badge-api shows no resources.

Hard Explain it like an interview

Why: Interviewers ask what you did, not what you read.

What to do: Record a 60 second answer about this lesson.

How:
  1. Say the problem.
  2. Say the YAML field or command.
  3. Say one error you hit and how you fixed it.

Check: Your answer has a real command and a real error in it.

Hard Draw the flow top to bottom

Why: A drawing shows if you know the order of things.

What to do: Draw this lesson as boxes from top to bottom on paper.

How:
  1. Start from the user curl.
  2. Go through Service, Pod, container.
  3. Mark where your error happened.

Check: Every arrow on your drawing matches a real object in kubectl get all.

Homework: try at home

Try at home

At home, do three updates (1.0, 1.1, 1.2) for the Python app, then undo to revision 1 with --to-revision=1.

Recap

  • Changing the Pod template starts a rollout.
  • Rolling update keeps the app up.
  • Old Pods serve until new ones are Ready.
  • rollout undo returns to the last good version.
  • Use fixed tags so each revision is clear.

FAQ

Does kubectl apply also roll out?

Yes, if the Pod template changed.

How many revisions are kept?

10 by default (revisionHistoryLimit).

Can I pause a rollout?

Yes, kubectl rollout pause and resume.

What is Recreate strategy?

Stop all old Pods, then start new. It causes downtime.

Does undo change my YAML in Git?

No. Fix Git too, or the next apply brings the bad version back.

Interview questions

  1. Explain a rolling update.

    Pods are replaced gradually based on maxSurge and maxUnavailable, so the service keeps running.

  2. How do you roll back?

    kubectl rollout undo deployment/NAME, optionally --to-revision.

  3. RollingUpdate vs Recreate?

    RollingUpdate has no downtime; Recreate stops all first.

  4. Why do readiness probes matter here?

    The rollout waits for new Pods to be Ready before removing old ones.

  5. How do you see rollout progress?

    kubectl rollout status.

Quick quiz

Q1. What does rolling update avoid?

Downtime.

Q2. Which command goes back?

kubectl rollout undo.

Q3. What does maxUnavailable 0 mean?

No Pod is taken down before a new one is Ready.

Q4. Where are revisions listed?

kubectl rollout history.

Q5. Does a broken tag take the app down?

No, old Pods keep serving.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards