Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Kubernetes Documentation

Run containers across many machines — pods, deployments, services, ingress, config and autoscaling.

Kubernetes (K8s) runs and manages containers across many machines. You describe the desired state in YAML ("3 copies of my API, reachable on port 80"), and Kubernetes keeps reality matching it: it schedules containers, restarts crashed ones, scales them, rolls out updates and load-balances traffic. Learn Docker first.

1. Introduction & Setup

Why Kubernetes?

Without K8s With K8s
SSH into servers to start containers declare what you want in YAML
a crashed container stays down self-healing — restarted automatically
manual scaling kubectl scale or autoscaling
downtime during deploys rolling updates and rollbacks
hard-coded IPs service discovery by name + load balancing

Local cluster options: minikube, kind (Kubernetes in Docker), Docker Desktop's built-in Kubernetes, k3d. Managed in the cloud: EKS (AWS), GKE (Google), AKS (Azure).

# install kubectl and minikube, then
minikube start
kubectl get nodes

Output:

NAME       STATUS   ROLES           AGE   VERSION
minikube   Ready    control-plane   40s   v1.31.0

⚠️ Common error: The connection to the server localhost:8080 was refused — no cluster is running or kubectl has no context. Start minikube/kind and check kubectl config current-context.

2. Architecture

                  ┌──────────── Control plane ────────────┐
kubectl ──► API server ── etcd (cluster state, key-value store)
                 │  scheduler (picks a node for each pod)
                 │  controller manager (keeps desired = actual)
                 ▼
   ┌─── Worker node ───┐   ┌─── Worker node ───┐
   │ kubelet           │   │ kubelet           │
   │ kube-proxy        │   │ kube-proxy        │
   │ container runtime │   │ container runtime │
   │ [pod] [pod]       │   │ [pod] [pod]       │
   └───────────────────┘   └───────────────────┘
Component Job
API server front door — every command goes through it
etcd stores the whole cluster state
Scheduler assigns new pods to nodes with enough resources
Controller manager runs control loops (Deployments, ReplicaSets, nodes)
kubelet agent on each node; starts pods and reports health
kube-proxy sets up networking rules for Services
Container runtime containerd / CRI-O actually runs containers

3. Pods

A Pod is the smallest unit — one (or a few tightly coupled) containers sharing an IP and storage. Pods are disposable; you rarely create them directly.

# pod.yaml
apiVersion: v1
kind: Pod
metadata:
  name: hello
  labels:
    app: hello
spec:
  containers:
    - name: web
      image: nginx:1.27
      ports:
        - containerPort: 80
kubectl apply -f pod.yaml
kubectl get pods
kubectl describe pod hello        # events, errors, IPs
kubectl logs hello
kubectl exec -it hello -- sh
kubectl delete pod hello

Every object has the same four parts: apiVersion, kind, metadata (name, labels), spec (desired state).

4. Deployments & ReplicaSets

A Deployment manages identical pods through a ReplicaSet: keeps N replicas running, replaces failed pods, and performs rolling updates.

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 3
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
        - name: api
          image: ghcr.io/codify/api:1.0.0
          ports:
            - containerPort: 5000
          env:
            - name: NODE_ENV
              value: production
          resources:
            requests: { cpu: "100m", memory: "128Mi" }
            limits:   { cpu: "500m", memory: "256Mi" }
          readinessProbe:
            httpGet: { path: /health, port: 5000 }
            initialDelaySeconds: 5
          livenessProbe:
            httpGet: { path: /health, port: 5000 }
            periodSeconds: 10
kubectl apply -f deployment.yaml
kubectl get deploy,rs,pods
kubectl scale deployment api --replicas=5
kubectl set image deployment/api api=ghcr.io/codify/api:1.1.0   # rolling update
kubectl rollout status deployment/api
kubectl rollout history deployment/api
kubectl rollout undo deployment/api                              # roll back
  • Rolling update: new pods start and become ready before old ones stop (maxSurge, maxUnavailable).
  • Readiness probe: "ready for traffic?" — failing pods are removed from the Service.
  • Liveness probe: "still alive?" — failing pods are restarted.
  • requests = guaranteed resources used for scheduling; limits = the maximum (memory over the limit → OOMKilled). 100m = 0.1 CPU core.

5. Services & Networking

Pods come and go with new IPs. A Service gives a stable name and IP and load-balances across pods that match its selector.

apiVersion: v1
kind: Service
metadata:
  name: api
spec:
  selector:
    app: api            # sends traffic to pods with this label
  ports:
    - port: 80          # service port
      targetPort: 5000  # container port
  type: ClusterIP
Type Reachable from
ClusterIP (default) inside the cluster only — http://api or api.default.svc.cluster.local
NodePort each node's IP on a port 30000–32767
LoadBalancer a cloud load balancer with a public IP
ExternalName a DNS alias to an outside service
kubectl get svc
kubectl port-forward svc/api 8080:80     # test locally: http://localhost:8080
minikube service api --url               # open a NodePort/LoadBalancer service in minikube

Network policies restrict which pods may talk to each other (default: all pods can reach all pods).

6. Ingress

An Ingress routes external HTTP(S) traffic to Services by host and path — one entry point for many services. It needs an ingress controller (e.g. ingress-nginx; minikube addons enable ingress).

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: codify
spec:
  ingressClassName: nginx
  tls:
    - hosts: [codify.example]
      secretName: codify-tls
  rules:
    - host: codify.example
      http:
        paths:
          - path: /api
            pathType: Prefix
            backend: { service: { name: api, port: { number: 80 } } }
          - path: /
            pathType: Prefix
            backend: { service: { name: web, port: { number: 80 } } }

TLS certificates are usually automated with cert-manager + Let's Encrypt. The newer Gateway API is the successor to Ingress for advanced routing.

7. ConfigMaps & Secrets

Keep configuration out of images.

apiVersion: v1
kind: ConfigMap
metadata:
  name: api-config
data:
  CLIENT_URL: https://codify.example
  LOG_LEVEL: info
---
apiVersion: v1
kind: Secret
metadata:
  name: api-secrets
type: Opaque
stringData:
  MONGO_URI: mongodb+srv://user:pass@cluster/db
  JWT_SECRET: change-me

Use them in a container:

envFrom:
  - configMapRef: { name: api-config }
  - secretRef: { name: api-secrets }
kubectl create secret generic api-secrets --from-literal=JWT_SECRET=abc --from-env-file=.env
kubectl get secret api-secrets -o yaml

⚠️ Secrets are only base64-encoded, not encrypted by default. Enable encryption at rest, restrict access with RBAC, and don't commit secret YAML to Git (use Sealed Secrets, External Secrets or the cloud's secret manager).

8. Storage: Volumes, PV & PVC

Container files vanish when a pod restarts. For data that must survive:

  • PersistentVolume (PV): a piece of storage (cloud disk, NFS).
  • PersistentVolumeClaim (PVC): a pod's request for storage ("10 GiB, ReadWriteOnce").
  • StorageClass: creates PVs automatically on demand (dynamic provisioning).
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mongo-data
spec:
  accessModes: [ReadWriteOnce]
  resources:
    requests:
      storage: 10Gi
# in the pod spec
volumes:
  - name: data
    persistentVolumeClaim: { claimName: mongo-data }
containers:
  - name: mongo
    image: mongo:7
    volumeMounts:
      - { name: data, mountPath: /data/db }

For databases use a StatefulSet (stable names mongo-0, mongo-1 and one PVC per replica) — or simply a managed database service.

9. Namespaces, Scaling & Other Workloads

Namespaces split one cluster into virtual groups (dev, staging, prod, per team):

kubectl create namespace dev
kubectl apply -f app.yaml -n dev
kubectl get pods -A                       # all namespaces
kubectl config set-context --current --namespace=dev

Horizontal Pod Autoscaler — add pods when CPU is high (needs metrics-server):

kubectl autoscale deployment api --cpu-percent=70 --min=2 --max=10
kubectl get hpa
Workload Use
Deployment stateless apps (APIs, web)
StatefulSet databases, Kafka — stable identity and storage
DaemonSet one pod on every node (log collectors, monitoring agents)
Job run to completion once (migration, report)
CronJob run on a schedule ("0 2 * * *" = 2 AM daily)

10. Advanced Concepts

  • Labels and selectors connect everything: Services → Pods, Deployments → ReplicaSets.
  • Helm: the package manager for Kubernetes — templated charts: helm install my-redis bitnami/redis.
  • Kustomize: patch base YAML per environment (kubectl apply -k overlays/prod).
  • RBAC: Roles/ClusterRoles + RoleBindings control who can do what; ServiceAccounts give pods identities.
  • GitOps: Argo CD / Flux sync the cluster from a Git repository.
  • Observability: Prometheus + Grafana (metrics), Loki/EFK (logs), OpenTelemetry (traces).
  • Pod disruption budgets, taints/tolerations, node affinity for placement and availability.
  • Init containers run setup before the main container; sidecars run alongside it (proxies, log shippers). Service meshes (Istio, Linkerd) add mTLS and traffic control.
  • When not to use Kubernetes: a single small app is simpler on Render, Railway, a VM with Docker Compose, or serverless.

11. Examples with Output

Example 1 — Create and expose a deployment

kubectl create deployment web --image=nginx:1.27 --replicas=2
kubectl expose deployment web --port=80 --type=NodePort
kubectl get pods -l app=web
NAME                   READY   STATUS    RESTARTS   AGE
web-6d4cf56db6-8kzt2   1/1     Running   0          12s
web-6d4cf56db6-q7x9m   1/1     Running   0          12s

Example 2 — Self-healing

kubectl delete pod web-6d4cf56db6-8kzt2
kubectl get pods -l app=web
NAME                   READY   STATUS    RESTARTS   AGE
web-6d4cf56db6-q7x9m   1/1     Running   0          2m
web-6d4cf56db6-zt5wl   1/1     Running   0          3s

The Deployment noticed only 1 of 2 replicas and created a new pod.

Example 3 — A crashing pod

kubectl get pods
NAME                  READY   STATUS             RESTARTS      AGE
api-7f9c6d8b5-xk2lp   0/1     CrashLoopBackOff   4 (30s ago)   2m

Debug with kubectl logs api-7f9c6d8b5-xk2lp --previous and kubectl describe pod … (often a missing env variable or a wrong command).

12. Practice Problems

  1. Start minikube or kind and run nginx as a Deployment with 3 replicas; delete a pod and watch it come back.
  2. Deploy your Node/Express API image with a ClusterIP Service and test it with port-forward.
  3. Move the API's settings into a ConfigMap and its secrets into a Secret.
  4. Add readiness and liveness probes; break /health and observe the behaviour.
  5. Perform a rolling update to a new image tag, then roll back.
  6. Run MongoDB with a PVC and confirm data survives a pod restart.
  7. Add an Ingress that routes /api to the API and / to the React front end.
  8. Configure an HPA and generate load to watch it scale.

13. Interview Questions

1. What is Kubernetes? An open-source container orchestration platform that automates deployment, scaling, self-healing and networking of containerised apps.

2. Pod vs container? A pod wraps one or more containers that share network and storage; it is the unit Kubernetes schedules.

3. Deployment vs StatefulSet? Deployments manage interchangeable stateless pods; StatefulSets give pods stable names, ordered start-up and their own persistent storage.

4. What are the Service types? ClusterIP (internal), NodePort (port on every node), LoadBalancer (cloud LB), ExternalName (DNS alias).

5. Liveness vs readiness probe? Liveness failure restarts the container; readiness failure removes the pod from Service endpoints until it's ready.

6. ConfigMap vs Secret? Both inject configuration; Secrets are meant for sensitive data (base64, can be encrypted at rest, tighter access).

7. How does a rolling update work? New ReplicaSet pods are created gradually while old ones are terminated, keeping the app available; rollout undo reverts.

8. What does etcd store? The entire cluster state — all objects and their configuration.

9. What is a namespace? A virtual partition of a cluster for organising resources and applying quotas and access rules.

10. What is CrashLoopBackOff? The container keeps crashing on start and Kubernetes is waiting longer between restarts; check logs and events.

14. Cheat Sheet & References

Cluster and context

kubectl cluster-info
kubectl get nodes
kubectl config get-contexts
kubectl config use-context minikube
kubectl get all -A

Apply and inspect

kubectl apply -f app.yaml
kubectl get pods -o wide
kubectl describe pod <name>
kubectl logs -f <pod> --previous
kubectl exec -it <pod> -- sh
kubectl delete -f app.yaml

Deployments

kubectl create deployment web --image=nginx --replicas=3
kubectl scale deploy web --replicas=5
kubectl set image deploy/web web=nginx:1.27
kubectl rollout status deploy/web
kubectl rollout undo deploy/web
kubectl autoscale deploy web --min=2 --max=10 --cpu-percent=70

Services and debugging

kubectl expose deploy web --port=80 --type=ClusterIP
kubectl port-forward svc/web 8080:80
kubectl get events --sort-by=.metadata.creationTimestamp
kubectl top pods
kubectl get pod <pod> -o yaml

Config

kubectl create configmap cfg --from-literal=LOG_LEVEL=info
kubectl create secret generic sec --from-env-file=.env
kubectl create namespace dev
kubectl get pods -n dev

Official documentation