Ravindra BagaleCourses & study guides मराठी

Chapter 15: Kubernetes Introduction

DevOps

15.11 Security basics (pointer)

Why: the problem

Suppose we are on the HDFC bank app team. One container is hacked through a bug. If it runs as root with full Linux powers, the attacker can do much more damage. A few lines in the YAML make the container much weaker for an attacker: run as a normal user, no privilege escalation, read-only filesystem, drop Linux capabilities.

What we will build

You will add a securityContext to all three stacks, prove the container is not root, and see what breaks and how to fix it.

What: every term in plain English

  • securityContext — Pod or container settings about users and permissions.
  • runAsNonRoot — Kubernetes refuses to start the container if it would run as root.
  • allowPrivilegeEscalation: false — A process cannot gain more power than its parent.
  • readOnlyRootFilesystem — The container cannot write to its own filesystem.
  • Capabilities — Small pieces of root power in Linux. Drop ALL for web apps.
  • RBAC — Rules for who can do what in the cluster.
See the user today Add the securityContext Apply Try to write a file Give the app a writable temp folder Check your own permissions Check as a service account
securityContext: non-root, no escalation, read-only, no capabilities

How: step by step

  1. See the user today

    kubectl exec deploy/badge-node -- id
    

    What it does: Our Dockerfile already sets USER node.

    Output

    uid=1000(node) gid=1000(node)
    
  2. Add the securityContext

    nano k8s/badge-node.yaml   # add Example 1 lines
    

    What it does: Locks down the container.

    Output

    (saved)
    
  3. Apply

    kubectl apply -f k8s/badge-node.yaml
    

    What it does: Pods restart with the new settings.

    Output

    deployment.apps/badge-node configured
    
  4. Try to write a file

    kubectl exec deploy/badge-node -- touch /app/x
    

    What it does: Read-only filesystem blocks it.

    Output

    touch: /app/x: Read-only file system
    command terminated with exit code 1
    
  5. Give the app a writable temp folder

    # add an emptyDir volume mounted at /tmp (see Example 2)
    

    What it does: Apps that need temp files get a small writable place.

    Output

    (saved)
    
  6. Check your own permissions

    kubectl auth can-i delete pods -n badge-api
    

    What it does: RBAC answers yes or no.

    Output

    yes
    
  7. Check as a service account

    kubectl auth can-i get secrets -n badge-api --as=system:serviceaccount:badge-api:default
    

    What it does: The default service account should not read Secrets.

    Output

    no
    

Example 1: Node

Stack. Node.js 20, Express, kind

Goal. Node.js: badge-node with a locked-down securityContext.

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: 2
  selector:
    matchLabels: { app: badge-node }
  template:
    metadata:
      labels: { app: badge-node }
    spec:
      volumes:
        - { name: tmp, emptyDir: {} }
      containers:
        - name: api
          image: badge-node:1.0
          ports:
            - containerPort: 3000
          securityContext:
            runAsNonRoot: true
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: { drop: ["ALL"] }
          volumeMounts:
            - { name: tmp, mountPath: /tmp }
---
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.
  • runAsNonRoot: true — Start fails if the image would run as root.
  • readOnlyRootFilesystem: true — No writes except to mounted volumes like /tmp.
  • capabilities drop ALL — No extra Linux powers.

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. The Node.js app still answers, and id shows a non-root user.

Example 2: Python: badge-py with a locked-down securityContext

Stack. Python 3.12, Flask, gunicorn, kind

Goal. Python: badge-py with a locked-down securityContext.

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: 2
  selector:
    matchLabels: { app: badge-py }
  template:
    metadata:
      labels: { app: badge-py }
    spec:
      volumes:
        - { name: tmp, emptyDir: {} }
      containers:
        - name: api
          image: badge-py:1.0
          ports:
            - containerPort: 5000
          securityContext:
            runAsNonRoot: true
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: { drop: ["ALL"] }
          volumeMounts:
            - { name: tmp, mountPath: /tmp }
---
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.
  • runAsNonRoot: true — Start fails if the image would run as root.
  • readOnlyRootFilesystem: true — No writes except to mounted volumes like /tmp.
  • capabilities drop ALL — No extra Linux powers.

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. The Python app still answers, and id shows a non-root user.

Example 3: Java: badge-java with a locked-down securityContext

Stack. Java 21, Spring Boot, kind

Goal. Java: badge-java with a locked-down securityContext.

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: 2
  selector:
    matchLabels: { app: badge-java }
  template:
    metadata:
      labels: { app: badge-java }
    spec:
      volumes:
        - { name: tmp, emptyDir: {} }
      containers:
        - name: api
          image: badge-java:1.0
          ports:
            - containerPort: 8080
          securityContext:
            runAsNonRoot: true
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: { drop: ["ALL"] }
          volumeMounts:
            - { name: tmp, mountPath: /tmp }
---
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.
  • runAsNonRoot: true — Start fails if the image would run as root.
  • readOnlyRootFilesystem: true — No writes except to mounted volumes like /tmp.
  • capabilities drop ALL — No extra Linux powers.

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. The Java app still answers, and id shows a non-root user.

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: container has runAsNonRoot and image will run as root

Cause. The image has no USER line, so it runs as root.

Fix, step by step

  1. Add a USER line in the Dockerfile (as in our Dockerfiles).
  2. Or set runAsUser: 10001.
  3. Build a new tag and roll it.

When it is red 2

OSError: [Errno 30] Read-only file system: '/app/cache'

Cause. The Python app writes to its own folder.

Fix, step by step

  1. Write to /tmp instead.
  2. Mount an emptyDir at /tmp.
  3. Apply and check logs.

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 Check the user

Why: Know who runs your app.

What to do: Run id in each stack.

How:
  1. kubectl exec deploy/NAME -- id

Check: No uid=0.

Medium Test readOnly

Why: See the block.

What to do: Try to touch a file.

How:
  1. kubectl exec ... touch /app/x

Check: Read-only error.

Hard Use Pod Security labels

Why: Namespace-wide rules.

What to do: Label the namespace restricted.

How:
  1. kubectl label ns badge-api pod-security.kubernetes.io/enforce=restricted

Check: Unsafe Pods are rejected.

Easy Say Pod security basics in two lines

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

What to do: Write two short lines about Pod security basics 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, run kubectl auth can-i --list as the default service account and list three things it can do.

Recap

  • Run as non-root.
  • Block privilege escalation.
  • Use a read-only root filesystem with a /tmp volume.
  • Drop all capabilities.
  • Check access with kubectl auth can-i.

FAQ

Does this make my app fully secure?

No. It limits damage. You still need patching, scans and RBAC.

Why did Java fail after read-only?

Java may write temp files. Mount /tmp.

What is Pod Security Admission?

Built-in namespace labels that enforce baseline or restricted rules.

Is USER in Dockerfile enough?

It helps. runAsNonRoot makes Kubernetes enforce it.

What is a service account?

An identity for Pods to call the Kubernetes API.

Interview questions

  1. Name four securityContext hardening settings.

    runAsNonRoot, allowPrivilegeEscalation false, readOnlyRootFilesystem, drop ALL capabilities.

  2. What is RBAC?

    Role-based access control: Roles and bindings that grant verbs on resources.

  3. What is Pod Security Admission?

    Namespace-level enforcement of privileged, baseline or restricted profiles.

  4. How do you check permissions?

    kubectl auth can-i.

  5. Why avoid privileged containers?

    They have near-host-level access.

Quick quiz

Q1. What does runAsNonRoot do?

Blocks containers that run as root.

Q2. Why drop capabilities?

Less power for an attacker.

Q3. How do apps write temp files with read-only root?

An emptyDir volume at /tmp.

Q4. Which command checks permissions?

kubectl auth can-i.

Q5. Should the default service account read Secrets?

No.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards