PART 1: CORE THEORY
1. The Workload Hierarchy
Kubernetes provides multiple workload types, each designed for a specific kind of application. Choosing the wrong one is a common source of production pain.
The Full Workload Family
text
┌─────────────────────────────────────────────────────────────┐
│ WORKLOAD TYPES │
│ │
│ STATELESS STATEFUL │
│ ┌───────────────┐ ┌───────────────┐ │
│ │ Deployment │ │ StatefulSet │ │
│ │ (ReplicaSet) │ │ (Ordered, │ │
│ │ │ │ Stable ID) │ │
│ └───────────────┘ └───────────────┘ │
│ │
│ NODE-LEVEL BATCH │
│ ┌───────────────┐ ┌───────────────┐ │
│ │ DaemonSet │ │ Job │ │
│ │ (One per │ │ CronJob │ │
│ │ node) │ │ (Scheduled) │ │
│ └───────────────┘ └───────────────┘ │
│ │
│ RAW │
│ ┌───────────────┐ │
│ │ Pod │ (Rarely used directly) │
│ └───────────────┘ │
└─────────────────────────────────────────────────────────────┘
Decision Matrix
| Workload | Stateless? | Identity? | Storage? | Ordering? | Use Case |
| Deployment | ✅ | ❌ | Shared | ❌ | Web apps, APIs |
| StatefulSet | ❌ | ✅ | Per-Pod | ✅ | Databases, queues |
| DaemonSet | ✅ | N/A | Node-local | N/A | Agents, CNI |
| Job | ✅ | ❌ | Optional | ❌ | Batch, migrations |
| CronJob | ✅ | ❌ | Optional | ❌ | Scheduled tasks |
| Pod | ✅ | ❌ | Optional | ❌ | Debugging |
The Controller Pattern
All workloads follow the same pattern:
text
User creates resource
│
▼
Controller observes
│
▼
Controller creates child resources (Pods, ReplicaSets)
│
▼
Controller reconciles continuously
Each workload is a controller with specific logic:
- Deployments → manage ReplicaSets → manage Pods
- StatefulSets → manage Pods with identity
- DaemonSets → manage Pods per node
- Jobs → manage Pods until completion
2. Deployments
A Deployment is the standard workload for stateless applications. It manages ReplicaSets, which manage Pods.
The Deployment → ReplicaSet → Pod Hierarchy
text
Deployment (web)
│
└── ReplicaSet (web-abc123) ← Current version
├── Pod web-abc123-1
├── Pod web-abc123-2
└── Pod web-abc123-3
│
└── ReplicaSet (web-def456) ← Old version (scaled to 0)
└── (0 pods)
Why ReplicaSets? They enable rolling updates and rollbacks. Each version of your Deployment gets its own ReplicaSet.
Deployment Strategies
| Strategy | Behavior | Downtime | Use Case |
| RollingUpdate | Gradual replacement | ❌ None | Default, production |
| Recreate | Kill all, then create new | ⚠️ Yes | Dev, incompatible versions |
RollingUpdate Parameters
yaml
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # Extra pods during update
maxUnavailable: 0 # Pods that can be down
The math:
| maxSurge | maxUnavailable | Behavior |
| 1 | 0 | Surge by 1, never drop below desired |
| 25% | 25% | Balanced (default) |
| 0 | 1 | No extra pods, one unavailable |
| 1 | 1 | Fast but risky |
For zero-downtime: maxUnavailable: 0 and at least 2 replicas.
The Update Lifecycle
text
1. User applies new Deployment (new image)
2. Deployment creates NEW ReplicaSet
3. New ReplicaSet scales up (respecting maxSurge)
4. Old ReplicaSet scales down (respecting maxUnavailable)
5. Repeat until new RS has all replicas, old RS has 0
6. Old RS is retained for rollback
Rollback and History
bash
# View history
kubectl rollout history deployment/web
# Rollback to previous
kubectl rollout undo deployment/web
# Rollback to specific revision
kubectl rollout undo deployment/web --to-revision=2
# Pause/resume (for multi-step changes)
kubectl rollout pause deployment/web
kubectl set image deployment/web web=nginx:1.26
kubectl set resources deployment/web --limits=cpu=500m
kubectl rollout resume deployment/web
# Restart (rolling restart)
kubectl rollout restart deployment/web
# Status
kubectl rollout status deployment/web
Revision History Limit
yaml
spec:
revisionHistoryLimit: 10 # Keep last 10 ReplicaSets (default)
Production tip: Keep enough history for rollback. 10 is usually fine; 5 for resource-constrained clusters.
Progress Deadline
yaml
spec:
progressDeadlineSeconds: 600 # Fail if not progressing in 10 min
If the rollout doesn't progress within this time, the Deployment is marked as failed. The ReplicaSet isn't deleted, but kubectl rollout status will exit with error.
Common Deployment Anti-Patterns
| Anti-Pattern | Why It's Bad |
| maxUnavailable: 100% | All pods down during update |
| replicas: 1 | No HA; every update is downtime |
| No readiness probe | Traffic routed to not-ready pods |
| revisionHistoryLimit: 0 | Can't rollback |
| :latest image tag | Non-deterministic updates |
| No resource requests/limits | Unpredictable scheduling |
3. StatefulSets
A StatefulSet manages stateful applications that require:
- Stable network identity
- Stable storage per replica
- Ordered deployment and scaling
The Identity Guarantee
| Aspect | Deployment | StatefulSet |
| Pod name | web-abc123-xyz (random) | web-0, web-1, web-2 (ordered) |
| Hostname | Same as Pod name | Same as Pod name (stable) |
| DNS | Random | web-0.web.default.svc.cluster.local |
| Storage | Shared or none | Per-Pod PVC (persistent) |
| Startup order | Parallel | Sequential (0 → 1 → 2) |
| Termination order | Parallel | Reverse (2 → 1 → 0) |
The Headless Service Requirement
StatefulSets require a Headless Service (clusterIP: None) for stable DNS.
yaml
apiVersion: v1
kind: Service
metadata:
name: db-headless
spec:
clusterIP: None
selector:
app: db
ports:
- port: 5432
name: postgres
Each Pod gets its own DNS record:
db-0.db-headless.default.svc.cluster.localdb-1.db-headless.default.svc.cluster.localdb-2.db-headless.default.svc.cluster.local
StatefulSet Example
yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
spec:
serviceName: postgres-headless
replicas: 3
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:16-alpine
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: pg-secret
key: password
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
ports:
- containerPort: 5432
name: postgres
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: fast-ssd
resources:
requests:
storage: 100Gi
Each Pod gets its own PVC: data-postgres-0, data-postgres-1, data-postgres-2. These PVCs are NOT deleted when the StatefulSet is deleted (data preservation).
Update Strategies
| Strategy | Behavior | Downtime |
| RollingUpdate | Update Pods in reverse order | ❌ None (if HA) |
| OnDelete | Manual Pod deletion triggers update | Manual control |
| Partitioned | Update only Pods ≥ partition | Canary releases |
Partitioned rolling update is the StatefulSet equivalent of canary:
yaml
spec:
updateStrategy:
type: RollingUpdate
rollingUpdate:
partition: 2 # Only update Pods with ordinal >= 2
This updates postgres-2 only, letting you validate before updating postgres-1 and postgres-0.
The Scaling Behavior
Scale up: Pods created in order 0, 1, 2 (each waits for the previous to be Ready).
Scale down: Pods deleted in reverse order 2, 1, 0.
When to Use StatefulSets
| Application | Why StatefulSet |
| PostgreSQL / MySQL | Needs stable storage per replica |
| MongoDB replica sets | Members need stable identities |
| Kafka / RabbitMQ | Brokers need stable IDs |
| Elasticsearch | Nodes need stable names |
| ZooKeeper / etcd | Consensus requires stable IDs |
| Cassandra | Ring topology needs ordering |
When NOT to Use StatefulSets
| Application | Use Instead |
| Stateless web app | Deployment |
| App with shared storage | Deployment + ReadWriteMany PVC |
| App without stable ID needs | Deployment |
The Operational Complexity
StatefulSets are harder to operate than Deployments:
| Challenge | Why |
| Ordered startup | Slow if 100 replicas |
| PVC management | PVCs persist after deletion |
| Data migration | No automatic data movement |
| Backup | Per-Pod backup needed |
| Debugging | Harder to reset (data persists) |
Rule of thumb: Use StatefulSet only if you need stable identity + per-Pod storage. Otherwise, use Deployment.
4. DaemonSets
A DaemonSet ensures a Pod runs on every node (or a subset). Used for node-level services.
How DaemonSets Work
text
Cluster with 5 nodes
│
▼
DaemonSet "fluentd" (replicas=5, implicit)
│
├── Pod on node-1
├── Pod on node-2
├── Pod on node-3
├── Pod on node-4
└── Pod on node-5
When a new node joins, a new Pod is automatically created. When a node leaves, its Pod is garbage collected.
Common DaemonSets
| DaemonSet | Purpose |
| kube-proxy | Networking |
| CNI plugin | Pod networking (Cilium, Calico) |
| CSI node plugin | Storage |
| Fluent Bit / Filebeat | Log collection |
| Prometheus Node Exporter | Node metrics |
| Datadog / New Relic agent | APM |
| Falco / Tetragon | Runtime security |
| NVIDIA device plugin | GPU scheduling |
DaemonSet Example
yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: node-exporter
namespace: monitoring
spec:
selector:
matchLabels:
app: node-exporter
template:
metadata:
labels:
app: node-exporter
spec:
hostNetwork: true
hostPID: true
tolerations:
- operator: Exists # Tolerate all taints
containers:
- name: node-exporter
image: prom/node-exporter:v1.7.0
args:
- "--path.procfs=/host/proc"
- "--path.sysfs=/host/sys"
- "--collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)"
ports:
- containerPort: 9100
hostPort: 9100
name: metrics
resources:
limits:
cpu: 200m
memory: 200Mi
requests:
cpu: 100m
memory: 100Mi
volumeMounts:
- name: proc
mountPath: /host/proc
readOnly: true
- name: sys
mountPath: /host/sys
readOnly: true
volumes:
- name: proc
hostPath:
path: /proc
- name: sys
hostPath:
path: /sys
The Toleration Requirement
DaemonSet Pods on control plane nodes need a toleration for the control-plane taint:
yaml
tolerations:
- key: node-role.kubernetes.io/control-plane
operator: Exists
effect: NoSchedule
Most DaemonSets use operator: Exists (tolerate all taints) to run on all nodes.
Node Selection
yaml
spec:
template:
spec:
nodeSelector:
node-type: gpu # Only on GPU nodes
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: topology.kubernetes.io/zone
operator: In
values: [us-east-1a, us-east-1b]
Update Strategies
| Strategy | Behavior |
| RollingUpdate | Update pods one node at a time |
| OnDelete | Update only when Pod is deleted |
yaml
spec:
updateStrategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1 # Update 1 node at a time
maxSurge: 0 # No extra Pods (fixed per node)
Note: DaemonSets don't support maxSurge > 0 because there's exactly one Pod per node.
DaemonSet Use Cases
| Use Case | Example |
| Log collection | Fluent Bit on every node |
| Metrics collection | node-exporter on every node |
| Networking | Cilium agent on every node |
| Storage | CSI node plugin on every node |
| Security | Falco on every node |
| GPU | NVIDIA device plugin on GPU nodes |
5. Jobs and CronJobs
Jobs
A Job runs Pods to completion. Unlike Deployments (which run forever), Jobs finish.
Job Patterns
| Pattern | Description |
| Single | One Pod runs to completion |
| Parallel fixed | N Pods complete successfully |
| Work queue | N workers process a queue |
| Indexed | Each Pod gets a unique index |
Single Job
yaml
apiVersion: batch/v1
kind: Job
metadata:
name: db-migrate
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: migrate
image: myapp:1.0
command: ["python", "manage.py", "migrate"]
Parallel Fixed
yaml
spec:
completions: 10 # Total successful completions needed
parallelism: 3 # Max concurrent Pods
Behavior: 3 Pods run concurrently. As each completes, a new one starts until 10 have succeeded.
Work Queue
yaml
spec:
parallelism: 5 # 5 workers
completions: 5 # Each worker processes until queue empty
# No completions specified = runs until all workers exit
Indexed Jobs (K8s 1.24+)
yaml
spec:
completions: 10
parallelism: 3
completionMode: Indexed
template:
spec:
containers:
- name: worker
image: myapp:1.0
env:
- name: JOB_COMPLETION_INDEX
valueFrom:
fieldRef:
fieldPath: metadata.annotations['batch.kubernetes.io/job-completion-index']
command: ["process.sh", "$(JOB_COMPLETION_INDEX)"]
Each Pod gets a unique index from 0 to completions-1. Perfect for sharded batch jobs.
Job Parameters
| Parameter | Purpose | Default |
| completions | Total successes needed | 1 |
| parallelism | Max concurrent Pods | 1 |
| backoffLimit | Retries before failure | 6 |
| activeDeadlineSeconds | Timeout for whole Job | None |
| ttlSecondsAfterFinished | Auto-delete after N seconds | None |
| completionMode | NonIndexed or Indexed | NonIndexed |
CronJobs
A CronJob creates Jobs on a schedule.
yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: backup
spec:
schedule: "0 2 * * *" # 2 AM daily
timeZone: "America/New_York" # Optional (K8s 1.27+)
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
startingDeadlineSeconds: 300
jobTemplate:
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: backup
image: backup-tool:1.0
command: ["/backup.sh"]
Cron Schedule Format
text
┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-6, Sun=0)
│ │ │ │ │
* * * * *
| Schedule | Meaning |
0 * * * * | Every hour |
0 0 * * * | Every day at midnight |
0 2 * * * | Every day at 2 AM |
0 0 * * 0 | Every Sunday |
0 0 1 * * | First of month |
*/15 * * * * | Every 15 minutes |
Concurrency Policy
| Policy | Behavior |
| Allow | Multiple Jobs run concurrently |
| Forbid | Skip if previous Job still running |
| Replace | Kill previous, start new |
CronJob Best Practices
| Practice | Why |
| Set concurrencyPolicy | Prevent overlap |
| Set startingDeadlineSeconds | Don't run too late |
| Use activeDeadlineSeconds | Prevent runaway jobs |
| Set resource limits | Predictable scheduling |
| Set ttlSecondsAfterFinished | Auto-cleanup |
| Use timeZone | Correct scheduling |
| Idempotent jobs | Safe retries |
Time Zones (K8s 1.27+)
yaml
spec:
schedule: "0 2 * * *"
timeZone: "America/New_York" # Schedules in EST
Without timeZone, schedules are in UTC.
6. Pod Lifecycle
Pod Phases
| Phase | Meaning |
| Pending | Accepted, waiting for scheduling or image pull |
| Running | At least one container running |
| Succeeded | All containers exited successfully (exit 0) |
| Failed | At least one container failed (exit ≠ 0) |
| Unknown | Can't determine state (usually node issue) |
Container States
| State | Meaning |
| Waiting | Not started (pulling image, waiting for dependency) |
| Running | Executing |
| Terminated | Finished or crashed |
Common Waiting Reasons
| Reason | Cause |
| ContainerCreating | Runtime is setting up |
| CrashLoopBackOff | Container keeps crashing |
| ImagePullBackOff | Can't pull image |
| ErrImagePull | Image pull error |
| CreateContainerConfigError | Bad config (missing ConfigMap/Secret) |
| CreateContainerError | Runtime failed to create |
| RunContainerError | Container failed to start |
| PodInitializing | Init containers still running |
The Full Lifecycle
text
1. User creates Pod
│
▼
2. Scheduler assigns to Node (Pending → Scheduled)
│
▼
3. Kubelet pulls images
│
▼
4. Init containers run sequentially
│
▼
5. Main containers start
│
▼
6. Startup probes (if defined) run
│
▼
7. Liveness and Readiness probes start
│
▼
8. Pod becomes Ready (Running → Ready)
│
▼
9. Terminating (when deleted or evicted)
│
▼
10. PreStop hook runs (if defined)
│
▼
11. SIGTERM sent to containers
│
▼
12. terminationGracePeriodSeconds wait
│
▼
13. SIGKILL if still running
│
▼
14. Pod removed
Restart Policy
| Policy | Behavior |
| Always | Restart on any exit (default for Deployments) |
| OnFailure | Restart only on non-zero exit |
| Never | Never restart |
Restart Backoff
Kubernetes uses exponential backoff for restarts:
text
1st restart: 10s
2nd: 20s
3rd: 40s
4th: 80s
5th: 160s
6th: 300s (max)
The restart counter resets after 10 minutes of successful running.
1:1 copy of the class Google Doc, code in code blocks.