Stage 1, Part 1 of 9 · p. 1, Kubernetes Fundamentals (Day 0/1)

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:

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:

The Kubernetes Guarantee

You tell Kubernetes:

Kubernetes handles:

When Kubernetes Is Overkill

ScenarioBetter Alternative
Single server, simple appDocker Compose
Static websiteNetlify, Vercel, S3+CloudFront
Simple scheduled jobsCron on a VM
Local developmentDocker Compose, Tilt
Serverless functionsLambda, 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

ComponentPurpose
kube-apiserverREST API, the front door to Kubernetes. All communication goes through it.
etcdDistributed key-value store. The single source of truth for cluster state.
kube-schedulerWatches for unscheduled Pods, assigns them to nodes.
kube-controller-managerRuns controller loops (Deployment, ReplicaSet, Node, etc.).
cloud-controller-managerIntegrates with cloud providers (AWS, GCP, Azure).

Worker Node Components

ComponentPurpose
kubeletAgent on each node. Watches for Pods assigned to its node, ensures containers are running.
kube-proxyManages networking (iptables/IPVS rules for Services).
Container RuntimeRuns containers (containerd, CRI-O). Docker is deprecated.
PodsThe 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:

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

PatternDescriptionUse Case
SidecarHelper container alongside mainLog shipper, proxy, watcher
AmbassadorProxy to external serviceDatabase proxy, API gateway
AdapterTransform outputMetrics exporter, log formatter
Init ContainersRun before main containersDB 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

PhaseMeaning
PendingPod accepted, waiting for scheduling or image pull
RunningAt least one container running
SucceededAll containers completed successfully
FailedAt least one container failed
UnknownState couldn't be determined

Container States

StateMeaning
WaitingNot started yet (pulling image, waiting for dependency)
RunningExecuting
TerminatedFinished or crashed

Common Waiting Reasons

ReasonMeaning
ContainerCreatingRuntime is setting up the container
CrashLoopBackOffContainer keeps crashing and restarting
ImagePullBackOffCan't pull the image
ErrImagePullImage pull error (usually auth)
CreateContainerConfigErrorInvalid config (missing ConfigMap/Secret)

Pod Restart Policy

PolicyBehavior
AlwaysRestart on any exit (default)
OnFailureRestart only on non-zero exit
NeverNever 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

ParameterMeaningDefault
maxSurgeHow many extra Pods during update25%
maxUnavailableHow many Pods can be unavailable25%

Zero-downtime formula:

text
replicas >= maxUnavailable + 1

For replicas: 3, maxUnavailable: 0, maxSurge: 1:

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:

  1. ✅ Readiness probes — Kubernetes knows when a Pod is ready
  2. ✅ maxUnavailable: 0 — Never drop below desired replicas
  3. ✅ Graceful shutdown — Pods handle SIGTERM, finish in-flight requests
  4. ✅ preStop hooks — Delay before SIGTERM
  5. ✅ PodDisruptionBudgets — Protect against voluntary disruptions
  6. ✅ 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?

ProblemService Solution
Pod IPs changeStable ClusterIP + DNS name
Need load balancingService distributes across Pods
Cross-pod communicationService discovery via DNS
External accessNodePort, LoadBalancer

The Four Service Types

TypeAccessibilityUse Case
ClusterIPInternal onlyDefault, service-to-service
NodePortVia node IP + portDevelopment, on-prem
LoadBalancerCloud LBProduction external access
ExternalNameDNS aliasExternal services

ClusterIP (Default)

yaml
apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  type: ClusterIP
  selector:
    app: nginx
  ports:
  - port: 80
    targetPort: 8080
    protocol: TCP

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:

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

  1. Service selects Pods via labels
  2. Kubernetes creates Endpoints objects (list of Pod IPs)
  3. kube-proxy programs iptables/IPVS rules
  4. 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

ConsumptionAuto-updates?
Env vars❌ No (requires Pod restart)
Volumes✅ Yes (within ~60s)

ConfigMap Best Practices

PracticeWhy
Use volumes for dynamic configAuto-updates
Use env vars for static configSimpler, no file I/O
Version control ConfigMapsGitOps
Don't store secretsUse Secrets instead
One ConfigMap per appEasier management
Use Helm/Kustomize for templatingAvoid 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

AspectConfigMapSecret
Data encodingPlain textBase64
Encryption at restOptionalOptional (but commonly enabled)
Size limit1 MB1 MB
Use caseNon-sensitive configPasswords, tokens, keys
Mount behaviorSameSame

Important: Secrets are not encrypted by default. They're base64-encoded, which is trivially decodable. Real security requires:

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

TypePurpose
OpaqueGeneric (default)
kubernetes.io/service-account-tokenServiceAccount tokens
kubernetes.io/dockercfgDocker registry credentials (legacy)
kubernetes.io/dockerconfigjsonDocker registry credentials
kubernetes.io/basic-authBasic auth
kubernetes.io/ssh-authSSH credentials
kubernetes.io/tlsTLS certificate + key
bootstrap.kubernetes.io/tokenBootstrap 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:

...can read them.

Real Secret Management

ApproachDescription
Encryption at restConfigure etcd encryption for Secrets
External Secrets OperatorSync from Vault, AWS Secrets Manager, etc.
Sealed SecretsEncrypt secrets in Git
SOPSEncrypt secrets with cloud KMS
Vault Agent InjectorInject 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.