Ravindra BagaleCourses & study guides मराठी

Chapter 15: Kubernetes Introduction

DevOps

15.2 Primary local tool — kind

Why: the problem

Suppose we are new at Infosys. The team says: practise Kubernetes, but do not touch the shared cluster. You need your own cluster on your laptop that is fast, free and easy to delete. Many tools exist: kind, minikube, k3d. If you jump between them, every guide looks different and you lose time. In this course we pick one: kind. kind means Kubernetes IN Docker. Each node is a Docker container.

What we will build

A kind cluster called badge-api with one control-plane node and two worker nodes, from a config file. Then you deploy the Node, Python and Java badge APIs into it.

What: every term in plain English

  • kind — A tool that creates Kubernetes clusters using Docker containers as nodes.
  • Control plane — The brain of the cluster: API server, scheduler and controllers.
  • Worker node — A node that runs your app Pods.
  • Context — A saved name in kubectl config that points to one cluster.
  • kubeconfig — The file ~/.kube/config that stores clusters and contexts.
  • kind config — A small YAML file that says how many nodes to create.
Check Docker works Check kind and kubectl Write the cluster config Create the cluster See the nodes See the nodes as containers Check the context
kind: Docker containers become Kubernetes nodes

How: step by step

  1. Check Docker works

    docker version --format "{{.Server.Version}}"
    

    What it does: kind needs a running Docker engine.

    Output

    27.1.1
    
  2. Check kind and kubectl

    kind version
    kubectl version --client
    

    What it does: Both tools must be installed from their official docs.

    Output

    kind v0.23.0 go1.22 linux/amd64
    Client Version: v1.30.2
    
  3. Write the cluster config

    cat > kind-badge.yaml <<YAML
    kind: Cluster
    apiVersion: kind.x-k8s.io/v1alpha4
    nodes:
      - role: control-plane
      - role: worker
      - role: worker
    YAML
    

    What it does: Asks for one control-plane and two workers.

    Output

    (no output - file saved)
    
  4. Create the cluster

    kind create cluster --name badge-api --config kind-badge.yaml
    

    What it does: Creates three Docker containers, one per node.

    Output

    Creating cluster "badge-api" ...
     ✓ Preparing nodes 📦 📦 📦
     ✓ Joining worker nodes 🚜
    Set kubectl context to "kind-badge-api"
    
  5. See the nodes

    kubectl get nodes
    

    What it does: All three should be Ready.

    Output

    NAME                      STATUS   ROLES           AGE   VERSION
    badge-api-control-plane   Ready    control-plane   60s   v1.30.0
    badge-api-worker          Ready    <none>          40s   v1.30.0
    badge-api-worker2         Ready    <none>          40s   v1.30.0
    
  6. See the nodes as containers

    docker ps --format "{{.Names}}"
    

    What it does: Proof that nodes are just containers.

    Output

    badge-api-control-plane
    badge-api-worker
    badge-api-worker2
    
  7. Check the context

    kubectl config current-context
    

    What it does: kubectl now talks to this cluster.

    Output

    kind-badge-api
    

Example 1: Node

Stack. Node.js 20, Express, kind

Goal. Node.js: deploy badge-node onto the 3-node kind cluster. Pods spread across the two workers.

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
  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.
  • kind load docker-image — Copies the image from your laptop into every kind node.

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. Three Node.js Pods Running. kubectl get pods -o wide shows them on badge-api-worker and badge-api-worker2.

Example 2: Python: deploy badge-py onto the 3-node kind cluster

Stack. Python 3.12, Flask, gunicorn, kind

Goal. Python: deploy badge-py onto the 3-node kind cluster. Pods spread across the two workers.

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
  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.
  • kind load docker-image — Copies the image from your laptop into every kind node.

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. Three Python Pods Running. kubectl get pods -o wide shows them on badge-api-worker and badge-api-worker2.

Example 3: Java: deploy badge-java onto the 3-node kind cluster

Stack. Java 21, Spring Boot, kind

Goal. Java: deploy badge-java onto the 3-node kind cluster. Pods spread across the two workers.

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
  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.
  • kind load docker-image — Copies the image from your laptop into every kind node.

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. Three Java Pods Running. kubectl get pods -o wide shows them on badge-api-worker and badge-api-worker2.

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: failed to create cluster: node(s) already exist for a cluster with the name "badge-api"

Cause. A cluster with that name already exists.

Fix, step by step

  1. Run kind get clusters.
  2. Use the existing one, or run kind delete cluster --name badge-api.
  3. Create it again.

When it is red 2

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

Cause. Docker is not running, so kind cannot create node containers.

Fix, step by step

  1. Start Docker Desktop or run sudo systemctl start docker.
  2. Run docker ps to check.
  3. Run kind create cluster again.

When it is red 3

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.

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 List your clusters

Why: Know what exists before you create more.

What to do: Run kind get clusters.

How:
  1. Run the command.
  2. Delete any you do not need.

Check: Only badge-api is listed.

Medium Use two clusters

Why: Contexts matter when you have more than one.

What to do: Create a second cluster called test and switch between them.

How:
  1. kind create cluster --name test
  2. kubectl config get-contexts
  3. kubectl config use-context kind-badge-api

Check: You can say which cluster kubectl points to.

Medium See Pod placement

Why: The scheduler spreads Pods.

What to do: Run kubectl get pods -o wide.

How:
  1. Look at the NODE column.

Check: Pods are on both workers.

Easy Say kind in two lines

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

What to do: Write two short lines about kind 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, create a kind cluster with one control-plane and three workers. Deploy the Python app with 6 replicas and count Pods per node with kubectl get pods -o wide.

Recap

  • kind runs each Kubernetes node as a Docker container.
  • A small config file sets the number of nodes.
  • kubectl uses the current context to pick a cluster.
  • Use kind load docker-image for local images.
  • Delete the cluster when you finish.

FAQ

Why kind and not minikube?

Both work. We use one tool so every step looks the same. kind is fast and fits CI too.

How much RAM do I need?

About 4 GB free is comfortable for a 3-node cluster.

Does kind work on Windows?

Yes, with Docker Desktop and WSL 2.

Is my data lost when I delete the cluster?

Yes. kind clusters are for practice.

Can I choose the Kubernetes version?

Yes, with --image kindest/node:v1.30.0.

Interview questions

  1. What is kind used for?

    Local and CI Kubernetes clusters where nodes are Docker containers.

  2. What is in the control plane?

    API server, etcd, scheduler and controller manager.

  3. What is a kubeconfig context?

    A pair of cluster and user that kubectl uses.

  4. How do you get a local image into kind?

    kind load docker-image, since kind nodes do not see the host image store.

  5. How do you check node health?

    kubectl get nodes and kubectl describe node.

Quick quiz

Q1. What does kind stand for?

Kubernetes IN Docker.

Q2. What is a kind node?

A Docker container.

Q3. Which file stores contexts?

~/.kube/config.

Q4. How do you load a local image?

kind load docker-image IMAGE --name CLUSTER.

Q5. How do you delete the cluster?

kind delete cluster --name badge-api.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards