PART 1: CORE THEORY
1. What is Kubernetes?
Kubernetes (K8s) is an open-source container orchestration platform originally developed by Google, now maintained by the CNCF. It automates the deployment, scaling, and management of containerized applications across a cluster of machines.
Why Kubernetes Exists
Before Kubernetes, running containers in production required:
- Manually scheduling containers onto machines
- Restarting containers when they crashed
- Load balancing across replicas
- Rolling updates without downtime
- Managing storage, secrets, and configuration
Kubernetes solves all of this with a declarative API: you describe what you want, and Kubernetes continuously works to make it true.
The Declarative Model
Imperative: "Start 3 containers on node-1"
Declarative: "I want 3 replicas of this app running at all times"
The declarative model is more powerful because Kubernetes:
- Continuously reconciles reality to match your desired state
- Recovers from failures automatically
- Provides a single source of truth for your infrastructure
The Kubernetes Guarantee
You tell Kubernetes:
- What image to run
- How many replicas
- What resources each needs
- How to expose it
Kubernetes handles:
- Scheduling onto nodes
- Health checks and restarts
- Rolling updates
- Service discovery
- Load balancing
- Scaling (with HPA)
- Secret distribution
When Kubernetes Is Overkill
| Scenario | Better Alternative |
| Single server, simple app | Docker Compose |
| Static website | Netlify, Vercel, S3+CloudFront |
| Simple scheduled jobs | Cron on a VM |
| Local development | Docker Compose, Tilt |
| Serverless functions | Lambda, Cloud Functions |
Kubernetes shines when: You have 5+ microservices, need high availability, have a team to operate it, and value portability.
2. The Kubernetes Architecture
The Two Planes
text
┌────────────────────────────────────────────────────┐
│ KUBERNETES ARCHITECTURE │
│ │
│ ┌─────────────────────────────────────────────┐ │
│ │ CONTROL PLANE (Brain) │ │
│ │ ┌─────────────┐ ┌────────────┐ │ │
│ │ │ API Server │ │ etcd │ │ │
│ │ │ (REST API) │ │ (State DB) │ │ │
│ │ └───────┬─────┘ └────────────┘ │ │
│ │ │ │ │
│ │ ┌───────┴─────┐ ┌────────────┐ │ │
│ │ │ Scheduler │ │ Controller │ │ │
│ │ │ │ │ Manager │ │ │
│ │ └─────────────┘ └────────────┘ │ │
│ └──────────────────────────┬─────────────────┘ │
│ │ │
│ │ API calls │
│ ▼ │
│ ┌─────────────────────────────────────────────┐ │
│ │ WORKER NODES (Muscle) │ │
│ │ ┌───────────────┐ ┌─────────────┐ │ │
│ │ │ kubelet │ │ kubelet │ │ │
│ │ │ kube-proxy │ │ kube-proxy │ │ │
│ │ │ container │ │ container │ │ │
│ │ │ runtime │ │ runtime │ │ │
│ │ │ Pods │ │ Pods │ │ │
│ │ └───────────────┘ └─────────────┘ │ │
│ └─────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────┘
Control Plane Components
| Component | Purpose |
| kube-apiserver | REST API, the front door to Kubernetes. All communication goes through it. |
| etcd | Distributed key-value store. The single source of truth for cluster state. |
| kube-scheduler | Watches for unscheduled Pods, assigns them to nodes. |
| kube-controller-manager | Runs controller loops (Deployment, ReplicaSet, Node, etc.). |
| cloud-controller-manager | Integrates with cloud providers (AWS, GCP, Azure). |
Worker Node Components
| Component | Purpose |
| kubelet | Agent on each node. Watches for Pods assigned to its node, ensures containers are running. |
| kube-proxy | Manages networking (iptables/IPVS rules for Services). |
| Container Runtime | Runs containers (containerd, CRI-O). Docker is deprecated. |
| Pods | The workloads themselves. |
The Request Flow
When you run kubectl apply -f deployment.yaml:
text
1. kubectl sends HTTP request to kube-apiserver
2. API server authenticates (who are you?)
3. API server authorizes (are you allowed?)
4. Admission controllers run (mutating → schema validation → validating)
5. Object is persisted to etcd
6. Controller Manager notices new Deployment, creates a ReplicaSet
7. ReplicaSet controller creates Pods
8. Scheduler notices unscheduled Pods, assigns them to nodes
9. kubelet on each node notices its Pods, tells runtime to start containers
10. kube-proxy updates networking for Services
The key insight: Everything is a controller watching the API server, reacting to changes.
3. Pods
A Pod is the smallest deployable unit in Kubernetes. It represents one or more containers that share the same network namespace, storage, and lifecycle.
Why Pods (Not Containers)?
Kubernetes doesn't schedule containers — it schedules Pods. A Pod is a wrapper that allows multiple containers to:
- Share a network namespace (localhost communication)
- Share volumes
- Share lifecycle (start/stop together)
A Simple Pod
yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25-alpine
ports:
- containerPort: 80
Multi-Container Pod Patterns
| Pattern | Description | Use Case |
| Sidecar | Helper container alongside main | Log shipper, proxy, watcher |
| Ambassador | Proxy to external service | Database proxy, API gateway |
| Adapter | Transform output | Metrics exporter, log formatter |
| Init Containers | Run before main containers | DB migrations, config setup |
Example: Multi-Container Pod
yaml
apiVersion: v1
kind: Pod
metadata:
name: web-with-sidecar
spec:
containers:
- name: web
image: nginx:1.25-alpine
ports:
- containerPort: 80
volumeMounts:
- name: logs
mountPath: /var/log/nginx
- name: log-shipper
image: fluent/fluent-bit:latest
volumeMounts:
- name: logs
mountPath: /var/log/nginx
readOnly: true
volumes:
- name: logs
emptyDir: {}
Pod Lifecycle Phases
| Phase | Meaning |
| Pending | Pod accepted, waiting for scheduling or image pull |
| Running | At least one container running |
| Succeeded | All containers completed successfully |
| Failed | At least one container failed |
| Unknown | State couldn't be determined |
Container States
| State | Meaning |
| Waiting | Not started yet (pulling image, waiting for dependency) |
| Running | Executing |
| Terminated | Finished or crashed |
Common Waiting Reasons
| Reason | Meaning |
| ContainerCreating | Runtime is setting up the container |
| CrashLoopBackOff | Container keeps crashing and restarting |
| ImagePullBackOff | Can't pull the image |
| ErrImagePull | Image pull error (usually auth) |
| CreateContainerConfigError | Invalid config (missing ConfigMap/Secret) |
Pod Restart Policy
| Policy | Behavior |
| Always | Restart on any exit (default) |
| OnFailure | Restart only on non-zero exit |
| Never | Never restart |
When to Use Pods Directly
Almost never. Pods are ephemeral — if a node dies, the Pod is gone. Use higher-level controllers (Deployments, StatefulSets) that manage Pods for you.
Exception: Debugging, one-shot jobs, or as templates for other controllers.
4. Deployments
A Deployment is a controller that manages a set of ReplicaSets, which in turn manage Pods. It provides declarative updates, rolling updates, and rollbacks.
The Controller Hierarchy
text
Deployment
│
└── ReplicaSet (v1)
├── Pod
├── Pod
└── Pod
When you update a Deployment, it creates a new ReplicaSet and gradually scales it up while scaling the old one down.
A Deployment
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25-alpine
ports:
- containerPort: 80
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
(Untitled part)
(Untitled part)
Rolling Update Strategy
| Parameter | Meaning | Default |
| maxSurge | How many extra Pods during update | 25% |
| maxUnavailable | How many Pods can be unavailable | 25% |
Zero-downtime formula:
text
replicas >= maxUnavailable + 1
For replicas: 3, maxUnavailable: 0, maxSurge: 1:
- Old Pods: 3 → 2 → 1 → 0
- New Pods: 0 → 1 → 2 → 3
- Total during update: 3 → 4 → 4 → 4 → 3
- No moment with fewer than 3 ready Pods.
Rollback
bash
# View history
kubectl rollout history deployment/nginx
# Rollback to previous
kubectl rollout undo deployment/nginx
# Rollback to specific revision
kubectl rollout undo deployment/nginx --to-revision=2
# Watch rollout
kubectl rollout status deployment/nginx
# Pause/resume rollout
kubectl rollout pause deployment/nginx
kubectl rollout resume deployment/nginx
Common Deployment Commands
bash
# Create
kubectl create deployment nginx --image=nginx:1.25-alpine --replicas=3
# Scale
kubectl scale deployment nginx --replicas=5
# Update image
kubectl set image deployment/nginx nginx=nginx:1.26-alpine
# Apply changes
kubectl apply -f deployment.yaml
# Rollout status
kubectl rollout status deployment/nginx
# Describe
kubectl describe deployment nginx
# View
kubectl get deployments
kubectl get rs
kubectl get pods -l app=nginx
The Revision History
Every Deployment change creates a new revision. Kubernetes keeps the last 10 revisions by default (revisionHistoryLimit: 10).
The Zero-Downtime Checklist
For a Deployment to be truly zero-downtime:
- ✅ Readiness probes — Kubernetes knows when a Pod is ready
- ✅ maxUnavailable: 0 — Never drop below desired replicas
- ✅ Graceful shutdown — Pods handle SIGTERM, finish in-flight requests
- ✅ preStop hooks — Delay before SIGTERM
- ✅ PodDisruptionBudgets — Protect against voluntary disruptions
- ✅ Multiple replicas — At least 2, ideally 3+
5. Services
Pods are ephemeral — their IPs change. A Service provides a stable virtual IP and DNS name that routes to a set of Pods (selected by labels).
Why Services?
| Problem | Service Solution |
| Pod IPs change | Stable ClusterIP + DNS name |
| Need load balancing | Service distributes across Pods |
| Cross-pod communication | Service discovery via DNS |
| External access | NodePort, LoadBalancer |
The Four Service Types
| Type | Accessibility | Use Case |
| ClusterIP | Internal only | Default, service-to-service |
| NodePort | Via node IP + port | Development, on-prem |
| LoadBalancer | Cloud LB | Production external access |
| ExternalName | DNS alias | External services |
ClusterIP (Default)
yaml
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: ClusterIP
selector:
app: nginx
ports:
- port: 80
targetPort: 8080
protocol: TCP
port: Port the Service listens ontargetPort: Port on the Pod to forward to
NodePort
yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-nodeport
spec:
type: NodePort
selector:
app: nginx
ports:
- port: 80
targetPort: 8080
nodePort: 30080
Accessible via <NodeIP>:30080. NodePorts range from 30000–32767 by default.
LoadBalancer
yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-lb
spec:
type: LoadBalancer
selector:
app: nginx
ports:
- port: 80
targetPort: 8080
Provisions a cloud load balancer (AWS ELB, GCP LB, etc.).
ExternalName
yaml
apiVersion: v1
kind: Service
metadata:
name: external-db
spec:
type: ExternalName
externalName: my-db.aws.rds.amazonaws.com
DNS-only. No proxying. Pods that call external-db get a CNAME to the external service.
Headless Services
clusterIP: None returns Pod IPs directly instead of a VIP. Used for StatefulSets where each Pod needs a stable identity.
yaml
apiVersion: v1
kind: Service
metadata:
name: db-headless
spec:
clusterIP: None
selector:
app: postgres
ports:
- port: 5432
Service DNS
Every Service gets a DNS name:
text
<service>.<namespace>.svc.cluster.local
Example: nginx.default.svc.cluster.local
Inside a Pod:
nginx— same namespacenginx.default— cross-namespacenginx.default.svc.cluster.local— FQDN
Port Forwarding for Debugging
bash
# Forward local port 8080 to Service port 80
kubectl port-forward svc/nginx 8080:80
# Forward to a specific Pod
kubectl port-forward pod/nginx-abc123 8080:80
Common Service Commands
bash
# List
kubectl get svc
kubectl get svc -A
# Describe
kubectl describe svc nginx
# Get endpoints (backing Pods)
kubectl get endpoints nginx
# Port forward
kubectl port-forward svc/nginx 8080:80
The Service → Endpoints Flow
- Service selects Pods via labels
- Kubernetes creates Endpoints objects (list of Pod IPs)
- kube-proxy programs iptables/IPVS rules
- Traffic to Service ClusterIP is load-balanced to Endpoints
bash
# Check endpoints
kubectl get endpoints nginx
# NAME ENDPOINTS AGE
# nginx 10.244.1.5:80,10.244.2.8:80,10.244.3.2:80 5m
Empty endpoints = Service can't find Pods. Common issue: wrong labels.
6. ConfigMaps
ConfigMaps hold non-sensitive configuration data as key-value pairs. They decouple configuration from container images, letting you change config without rebuilding.
Creating a ConfigMap
From YAML:
yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
app.properties: |
log.level=INFO
server.port=8080
cache.enabled=true
DATABASE_HOST: db.example.com
DATABASE_PORT: "5432"
From literal values:
bash
kubectl create configmap app-config \
--from-literal=DATABASE_HOST=db.example.com \
--from-literal=DATABASE_PORT=5432
From files:
bash
kubectl create configmap app-config --from-file=config.properties
Consuming ConfigMaps
As environment variables:
yaml
spec:
containers:
- name: app
image: myapp:1.0
env:
- name: DATABASE_HOST
valueFrom:
configMapKeyRef:
name: app-config
key: DATABASE_HOST
# Or inject all keys as env vars
envFrom:
- configMapRef:
name: app-config
As volume mounts:
yaml
spec:
containers:
- name: app
image: myapp:1.0
volumeMounts:
- name: config
mountPath: /etc/config
readOnly: true
volumes:
- name: config
configMap:
name: app-config
With this pattern, each key becomes a file in /etc/config/.
ConfigMap Update Behavior
| Consumption | Auto-updates? |
| Env vars | ❌ No (requires Pod restart) |
| Volumes | ✅ Yes (within ~60s) |
ConfigMap Best Practices
| Practice | Why |
| Use volumes for dynamic config | Auto-updates |
| Use env vars for static config | Simpler, no file I/O |
| Version control ConfigMaps | GitOps |
| Don't store secrets | Use Secrets instead |
| One ConfigMap per app | Easier management |
| Use Helm/Kustomize for templating | Avoid hardcoding |
ConfigMap Size Limit
The total size of a ConfigMap (and Secret) is 1 MB. For larger configs, use a volume, an init container to download, or a ConfigMap-referencing sidecar.
7. Secrets
Secrets are like ConfigMaps but for sensitive data (passwords, tokens, keys, certificates).
How Secrets Differ from ConfigMaps
| Aspect | ConfigMap | Secret |
| Data encoding | Plain text | Base64 |
| Encryption at rest | Optional | Optional (but commonly enabled) |
| Size limit | 1 MB | 1 MB |
| Use case | Non-sensitive config | Passwords, tokens, keys |
| Mount behavior | Same | Same |
Important: Secrets are not encrypted by default. They're base64-encoded, which is trivially decodable. Real security requires:
- Encryption at rest (etcd encryption)
- RBAC restrictions
- External secret stores (Vault, AWS Secrets Manager)
Creating a Secret
From literals:
bash
kubectl create secret generic db-secret \
--from-literal=username=admin \
--from-literal=password='S3cret!' \
--from-literal=host=db.example.com
From files:
bash
kubectl create secret generic tls-secret \
--from-file=tls.crt=./server.crt \
--from-file=tls.key=./server.key
From YAML:
yaml
apiVersion: v1
kind: Secret
metadata:
name: db-secret
type: Opaque
data:
username: YWRtaW4= # base64: admin
password: UzNjcmV0IQ== # base64: S3cret!
stringData: # Or use stringData for plaintext (auto-encoded)
host: db.example.com
Secret Types
| Type | Purpose |
| Opaque | Generic (default) |
| kubernetes.io/service-account-token | ServiceAccount tokens |
| kubernetes.io/dockercfg | Docker registry credentials (legacy) |
| kubernetes.io/dockerconfigjson | Docker registry credentials |
| kubernetes.io/basic-auth | Basic auth |
| kubernetes.io/ssh-auth | SSH credentials |
| kubernetes.io/tls | TLS certificate + key |
| bootstrap.kubernetes.io/token | Bootstrap tokens |
Consuming Secrets
As environment variables:
yaml
spec:
containers:
- name: app
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-secret
key: password
As volume mounts:
yaml
spec:
containers:
- name: app
volumeMounts:
- name: secret
mountPath: /etc/secrets
readOnly: true
volumes:
- name: secret
secret:
secretName: db-secret
defaultMode: 0400
Secrets Are Not Truly Secret
By default, Secrets are stored unencrypted in etcd. Anyone with:
- Access to etcd
- Cluster admin RBAC
- Access to node's disk
...can read them.
Real Secret Management
| Approach | Description |
| Encryption at rest | Configure etcd encryption for Secrets |
| External Secrets Operator | Sync from Vault, AWS Secrets Manager, etc. |
| Sealed Secrets | Encrypt secrets in Git |
| SOPS | Encrypt secrets with cloud KMS |
| Vault Agent Injector | Inject Vault secrets into Pods |
The Docker Registry Secret
bash
kubectl create secret docker-registry regcred \
--docker-server=myregistry.example.com \
--docker-username=alice \
--docker-password=secret \
--docker-email=alice@example.com
Use it in a Pod:
yaml
spec:
imagePullSecrets:
- name: regcred
containers:
- name: app
image: myregistry.example.com/myapp:1.0
TLS Secret
For Ingress TLS, the Secret must be named kubernetes.io/tls type:
yaml
apiVersion: v1
kind: Secret
metadata:
name: tls-secret
type: kubernetes.io/tls
data:
tls.crt: <base64-cert>
tls.key: <base64-key>
1:1 copy of the class Google Doc, code in code blocks.