Chapter 15: Kubernetes Introduction
15.3 Core objects — Pod, Deployment, Service, Namespace
Why: the problem
Suppose we open the Netflix app. Behind it, thousands of small programs run. Someone must say where each program runs, how many copies there are, and how others find it. In Kubernetes this is done with four basic objects: Pod, Deployment, Service and Namespace. If you mix them up, nothing else makes sense. So we build each one, one by one, for the badge API.
What we will build
In the badge-api namespace you will create a bare Pod, then a Deployment that makes Pods for you, then a Service that gives them one name. You will see why a bare Pod is not enough.
What: every term in plain English
- Pod — The smallest thing Kubernetes runs. One or more containers that share network and storage.
- Deployment — Keeps a number of identical Pods running and handles updates.
- ReplicaSet — Made by the Deployment. It counts Pods and makes more when needed.
- Service — A stable name and IP in front of a changing set of Pods.
- Namespace — A folder that separates teams or apps inside one cluster.
- Label — A key=value tag on an object, like app=badge-node. Services find Pods by labels.
How: step by step
-
Create a bare Pod
kubectl -n badge-api run solo --image=badge-node:1.0 --port=3000What it does: Makes one Pod with no Deployment.
Output
pod/solo created -
Delete it and see it is gone
kubectl -n badge-api delete pod solo kubectl -n badge-api get podsWhat it does: A bare Pod is not replaced. Nobody owns it.
Output
pod "solo" deleted No resources found in badge-api namespace. -
Apply a Deployment
kubectl apply -f k8s/badge-node.yamlWhat it does: Now a Deployment owns the Pods.
Output
deployment.apps/badge-node created service/badge-node created -
See the chain Deployment to ReplicaSet to Pod
kubectl -n badge-api get deploy,rs,podsWhat it does: Three layers, each owning the next.
Output
deployment.apps/badge-node 2/2 replicaset.apps/badge-node-6d9f7c8b5 2 2 2 pod/badge-node-6d9f7c8b5-4kq2x 1/1 Running -
See the labels
kubectl -n badge-api get pods --show-labelsWhat it does: The app label links Pods to the Service.
Output
NAME READY LABELS badge-node-6d9f7c8b5-4kq2x 1/1 app=badge-node,pod-template-hash=6d9f7c8b5 -
See the Service
kubectl -n badge-api get svc badge-nodeWhat it does: A fixed ClusterIP that does not change when Pods change.
Output
NAME TYPE CLUSTER-IP PORT(S) badge-node ClusterIP 10.96.41.12 80/TCP -
Call the Service from inside the cluster
kubectl -n badge-api run tmp --rm -it --image=curlimages/curl --restart=Never -- curl -s badge-node/healthWhat it does: A temporary Pod calls the Service by its name.
Output
{"status":"ok"} pod "tmp" deleted
Example 1: Node
Stack. Node.js 20, Express, kind
Goal. Node.js: Pod, Deployment and Service for badge-node. You apply one file and get all three layers.
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:
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.
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. kubectl get deploy,rs,pods,svc shows the full chain for Node.js.
Example 2: Python: Pod, Deployment and Service for badge-py
Stack. Python 3.12, Flask, gunicorn, kind
Goal. Python: Pod, Deployment and Service for badge-py. You apply one file and get all three layers.
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:
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.
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. kubectl get deploy,rs,pods,svc shows the full chain for Python.
Example 3: Java: Pod, Deployment and Service for badge-java
Stack. Java 21, Spring Boot, kind
Goal. Java: Pod, Deployment and Service for badge-java. You apply one file and get all three layers.
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:
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.
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. kubectl get deploy,rs,pods,svc shows the full chain for Java.
Verify: did it work?
-
List everything in the namespace
kubectl -n badge-api get allWhat 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 -
Check that the Service found the Pods
kubectl -n badge-api get endpoints badge-nodeWhat 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 -
Call the app through the Service
kubectl -n badge-api port-forward svc/badge-node 8080:80 & curl -s localhost:8080/healthWhat 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
$ kubectl -n badge-api get endpoints badge-java
NAME ENDPOINTS AGE
badge-java <none> 5m
Cause. The Service selector does not match the Pod labels, so the Service has no Pods behind it.
Fix, step by step
- Run kubectl get pods --show-labels.
- Compare the label with spec.selector in the Service.
- Fix the typo and apply again. Endpoints should now list Pod IPs.
When it is red 2
Error from server (NotFound): namespaces "badge-api" not found
Cause. The namespace does not exist yet.
Fix, step by step
- Run kubectl create namespace badge-api.
- Apply the file 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
- Run kubectl describe pod and read the Events at the bottom.
- Check the tag in the YAML matches docker images.
- Run kind load docker-image badge-node:1.0 --name badge-api.
- Run kubectl rollout restart deployment/badge-node -n badge-api.
Cleanup
-
Stop the port-forward
kill %1What it does: Ends the background tunnel.
Output
[1]+ Terminated kubectl port-forward svc/badge-node 8080:80 -
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 -
Delete the cluster at the end of the day
kind delete cluster --name badge-apiWhat it does: Removes the kind node container and frees memory.
Output
Deleting cluster "badge-api" ... Deleted nodes: ["badge-api-control-plane"]
Practice tasks
Easy Draw the four objects
Why: Pictures help you remember.
What to do: Draw Namespace, Deployment, Pod, Service.
- Use boxes and arrows.
Check: Arrows match ownership.
Medium Break the label
Why: Labels are the glue.
What to do: Change the Service selector to app=badge-nod.
- Apply.
- kubectl get endpoints.
Check: Endpoints is <none>.
Medium Find the owner
Why: ownerReferences show who owns what.
What to do: Read the owner of a Pod.
- kubectl get pod NAME -o yaml | grep -A3 ownerReferences
Check: It shows a ReplicaSet.
Easy Say Pod, Deployment, Service and Namespace in two lines
Why: If you can say it simply, you understand it.
What to do: Write two short lines about Pod, Deployment, Service and Namespace for a fresher.
- Write the problem it solves.
- 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.
- kind delete cluster --name badge-api
- kind create cluster --name badge-api
- 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.
- Build the image with a 1.0 tag.
- kind load docker-image the image.
- 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.
- Change the tag to 9.9.
- kubectl apply -f the file.
- 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.
- kubectl delete -f k8s/
- kubectl get all -n badge-api
- 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.
- Say the problem.
- Say the YAML field or command.
- 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.
- Start from the user curl.
- Go through Service, Pod, container.
- 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, write the four objects on paper with one arrow each. Then create them for the Java app and match each box to a line of kubectl get all.
Recap
- A Pod runs containers. It is the smallest unit.
- A Deployment keeps Pods alive through a ReplicaSet.
- A Service gives a stable name using labels.
- A Namespace separates apps.
- Never run bare Pods for real apps.
FAQ
Can a Pod have two containers?
Yes, for helpers like a log shipper. Most Pods have one.
Why does the Pod name change?
New Pods get new random names. That is why we use Services.
Is a Service a load balancer?
Inside the cluster it spreads traffic across Pods, yes.
Should I make one namespace per app?
A common start is one per team or app and environment.
What is pod-template-hash?
A label the Deployment adds to tell ReplicaSet versions apart.
Interview questions
-
Pod vs Deployment?
A Pod is one running unit. A Deployment manages many Pods and their updates.
-
Why do we need Services?
Pod IPs change. A Service gives a stable IP and DNS name and spreads traffic.
-
What is a ReplicaSet?
It keeps the number of Pods equal to replicas. Deployments create them.
-
What are labels and selectors?
Tags on objects and queries over tags. Services and Deployments use them to find Pods.
-
Why use namespaces?
To separate teams and environments and apply quotas and access rules.
Quick quiz
Q1. What is the smallest unit Kubernetes runs?
A Pod.
Q2. Who replaces a deleted Pod?
The ReplicaSet made by the Deployment.
Q3. How does a Service find Pods?
By label selector.
Q4. What is a Namespace?
A folder that separates objects inside a cluster.
Q5. Is a bare Pod replaced when deleted?
No.
Did you understand? Let us try it once more.
Revision card
Interview card