Kubernetes: The Giant Coordinator
When one container isn't enough, Kubernetes runs thousands of them β reliably.
What you'll learn in this chapter
- Why Docker alone is not enough at scale, and what problem Kubernetes solves
- The architecture of a Kubernetes cluster: the control plane and worker nodes
- Core Kubernetes objects: Pods, Deployments, Services, Ingress, ConfigMaps, Secrets
- How to write YAML manifests for real-world workloads
- How to use kubectl β the Kubernetes command-line tool
- Liveness and readiness probes for self-healing applications
- Horizontal Pod Autoscaling and namespace isolation
- Managed Kubernetes services: EKS, GKE, and AKS
The Toy Room Manager Analogy
Imagine a giant playroom with a hundred different kinds of toys to keep organized. The rules are specific: there must always be exactly five red cars on the shelf. If a child takes one, put another one there. If one breaks, replace it immediately. When more children arrive for a birthday party, double the number of red cars temporarily. Late at night when fewer children are around, reduce to two to save space.
Without a manager, this chaos would consume a human full-time. With a good manager, you just state the rules once and walk away. The manager watches constantly, detects when the real state differs from the required state, and fixes it β without being asked.
Kubernetes is that manager, for your containers. You tell it: "I need three copies of my web server always running. Each one needs 256MB of memory and 0.5 CPU cores. If one crashes, restart it. If CPU exceeds 70%, add more copies. Route HTTP traffic to them at myapp.example.com." You write that down in a YAML file. Kubernetes reads it, makes it happen, and keeps it that way β forever.
You state the desired state: "5 red cars on the shelf, always." Kubernetes continuously watches the actual state and reconciles any differences. A container crashes? Kubernetes notices the actual count dropped to 4 and immediately starts a new one. This loop β desired state vs actual state, fix the difference β is the core idea behind everything Kubernetes does.
Why Docker Alone Isn't Enough
Docker is excellent for running containers on a single machine. But production applications face challenges that a single machine cannot solve alone.
What happens when your container crashes at 3 AM? With plain Docker, it stays down until a human SSHes in and restarts it. What happens when traffic spikes and one server isn't enough? You need to distribute load across many servers. What happens when you deploy a new version? You need to replace old containers with new ones without dropping any requests. What happens when Server A runs out of disk space but Server B has plenty? You need to intelligently schedule containers to the right machines.
Kubernetes solves all of these. It is a container orchestrator β it manages fleets of containers across fleets of machines, making decisions automatically that would otherwise require constant human attention.
Kubernetes (often abbreviated as K8s β "K" + 8 letters + "s") is an open-source container orchestration platform originally developed at Google and donated to the Cloud Native Computing Foundation (CNCF). It automates the deployment, scaling, and management of containerized applications across clusters of machines. The name comes from the Greek word for "helmsman" or "pilot."
The Kubernetes Architecture
A Kubernetes cluster is a group of machines (physical or virtual) that work together. These machines fall into two roles: the control plane and the worker nodes.
The Control Plane β The Manager's Office
The control plane is the brain of the cluster. It is where decisions are made. You normally never run application workloads on control plane nodes β they exist purely to coordinate everything else.
- kube-apiserver β the front desk. Every request to the cluster (from kubectl, from other components, from ArgoCD) goes through the API server. It validates requests and stores the results in etcd.
- etcd β the filing cabinet. A distributed key-value store that holds the entire state of the cluster: every object definition, every status update. If etcd is lost without a backup, your cluster state is gone.
- kube-scheduler β decides which worker node each new Pod should run on. It considers available resources, affinity rules, and taints/tolerations to make the best placement decision.
- kube-controller-manager β a collection of controllers that run reconciliation loops. The Deployment controller watches Deployments and ensures the right number of Pods exist. The ReplicaSet controller ensures replicas match the desired count. There are dozens of controllers, each watching one type of object.
Worker Nodes β The Workshop Floors
Worker nodes are the machines that actually run your application containers.
- kubelet β the floor manager of each node. It receives Pod assignments from the scheduler and tells the container runtime to start or stop containers. It also runs health checks and reports node status back to the API server.
- kube-proxy β handles networking. It maintains network rules that allow Pods to communicate with each other and with Services.
- Container runtime β the software that actually runs containers. Most modern clusters use containerd (the same runtime Docker uses under the hood).
KUBERNETES CLUSTER ARCHITECTURE
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CONTROL PLANE β
β βββββββββββββββββ βββββββββ βββββββββββββ ββββββββββββββββ β
β β kube-apiserverβ β etcd β β scheduler β β controller β β
β β (front desk) β β (DB) β β (placer) β β manager β β
β βββββββββ¬ββββββββ βββββββββ βββββββββββββ ββββββββββββββββ β
ββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β API calls
ββββββββ΄ββββββββββββββββββββββββββββββββββ
β β
βββββΌβββββββββββββββ ββββββββββββΌββββββββββββ
β WORKER NODE A β β WORKER NODE B β
β βββββββββββββββ β β βββββββββββββββββββ β
β β kubelet β β β β kubelet β β
β βββββββββββββββ€ β β βββββββββββββββββββ€ β
β β kube-proxy β β β β kube-proxy β β
β βββββββββββββββ€ β β βββββββββββββββββββ€ β
β β Pod A β β β β Pod B Pod C β β
β β [app:v2] β β β β [app:v2][db] β β
β βββββββββββββββ β β βββββββββββββββββββ β
ββββββββββββββββββββ ββββββββββββββββββββββββ
Core Kubernetes Objects
Kubernetes manages your applications through a set of abstract objects, each defined in YAML. You declare what you want; Kubernetes makes it real. Here are the objects you will use in every production deployment.
Pod β The Smallest Deployable Unit
A Pod is one or more containers that share the same network namespace and storage.
They always run together on the same node and can communicate with each other via
localhost. In practice, most Pods contain a single container. You almost
never create Pods directly β you create Deployments, which create Pods for you.
apiVersion: v1
kind: Pod
metadata:
name: my-app
labels:
app: my-app
spec:
containers:
- name: app
image: myapp:1.0
ports:
- containerPort: 3000
Deployment β Managed Pods with Rolling Updates
A Deployment says: "run N copies of this Pod, and if I push an update, replace them one by one without downtime." It creates a ReplicaSet behind the scenes to manage the Pods. When you update the image tag in a Deployment, Kubernetes starts Pods with the new image and terminates the old ones gradually β a rolling update.
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
namespace: production
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: app
image: myapp:1.0
ports:
- containerPort: 3000
resources:
requests:
memory: "64Mi" # minimum memory to reserve on the node
cpu: "250m" # 250 millicores = 0.25 CPU cores
limits:
memory: "128Mi" # hard cap β container killed if exceeded
cpu: "500m" # hard cap β container throttled if exceeded
Without resource requests, the scheduler cannot make good placement decisions. Without limits, a runaway container can consume all memory on a node and crash every other Pod running there. Always set both. Use requests to represent normal usage, and limits to represent the maximum your app should ever need.
Service β Stable Network Address for Your Pods
Pods are ephemeral β they are created and destroyed constantly. Every time a Pod is replaced, it gets a new IP address. A Service is an abstraction that gives your Pods a stable endpoint. It acts as a load balancer in front of all Pods that match a label selector.
apiVersion: v1
kind: Service
metadata:
name: my-app-service
namespace: production
spec:
selector:
app: my-app # routes traffic to any Pod with this label
ports:
- port: 80 # the Service's port (other services call port 80)
targetPort: 3000 # forwards to container's port 3000
type: ClusterIP # only accessible within the cluster
Service types control how the Service is exposed:
- ClusterIP β default. Reachable only from within the cluster. Use this for internal services like a database or cache.
- NodePort β exposes the service on a port on each node. Accessible from outside but awkward to use in practice.
- LoadBalancer β provisions a cloud load balancer (an AWS ELB, GCP Load Balancer, etc.) automatically. The standard way to expose a service to the internet.
Ingress β HTTP Routing at the Edge
An Ingress is a set of rules for routing external HTTP/HTTPS traffic to internal Services.
Instead of one LoadBalancer per service (expensive and unwieldy), you have one Ingress
Controller (like nginx or Traefik) that handles all external traffic and routes it based
on the hostname and path. All of myapp.example.com/api goes to the API service;
myapp.example.com/ goes to the frontend service.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-ingress
namespace: production
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
cert-manager.io/cluster-issuer: "letsencrypt-prod" # auto TLS
spec:
tls:
- hosts: [myapp.example.com]
secretName: myapp-tls
rules:
- host: myapp.example.com
http:
paths:
- path: /api
pathType: Prefix
backend:
service:
name: api-service
port:
number: 80
- path: /
pathType: Prefix
backend:
service:
name: frontend-service
port:
number: 80
ConfigMap and Secret β Separating Config from Code
Hardcoding configuration into your Docker image is an antipattern. You want a single image that can run in staging with one database URL and in production with a different one. ConfigMaps and Secrets hold that configuration outside the image, injected into containers at runtime.
--- ConfigMap: non-sensitive configuration
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
DATABASE_HOST: "postgres.production.svc.cluster.local"
LOG_LEVEL: "info"
MAX_CONNECTIONS: "100"
--- Secret: sensitive data (stored base64-encoded)
apiVersion: v1
kind: Secret
metadata:
name: app-secrets
type: Opaque
data:
DB_PASSWORD: c3VwZXJzZWNyZXQ= # base64("supersecret")
JWT_SECRET: bXlqd3RzZWNyZXQ= # base64("myjwtsecret")
Inject them into your containers either as environment variables or as mounted files:
containers:
- name: app
image: myapp:1.0
envFrom:
- configMapRef:
name: app-config # all ConfigMap keys become env vars
- secretRef:
name: app-secrets # all Secret keys become env vars
Kubernetes Secrets are only base64-encoded β not encrypted. Anyone with access to etcd or with the right RBAC permissions can read them. For real security, use Sealed Secrets (from Bitnami), HashiCorp Vault, or enable etcd encryption at rest. Treat Kubernetes Secrets as a step above ConfigMaps β but not as a substitute for a proper secrets management system in high-security environments.
HorizontalPodAutoscaler β Scaling Based on Load
An HPA watches a Deployment and automatically adjusts the replica count based on metrics. When CPU utilization exceeds your target (say 70%), it adds Pods. When it drops back down, it removes them. This is automatic scaling β you set the rules, Kubernetes responds to traffic.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 2 # never go below 2 (for availability)
maxReplicas: 20 # never scale beyond 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70 # scale up when avg CPU > 70%
kubectl β The Kubernetes Command Line
kubectl (pronounced "cube control" or "cube CTL") is your window into the cluster.
Everything you can do through a UI, you can do with kubectl β and much more. Learn these
commands and you will be comfortable in any Kubernetes environment.
# Apply a manifest file (creates or updates the resource)
kubectl apply -f deployment.yaml
# Apply all files in a directory
kubectl apply -f ./k8s/
# Get resources β the most commonly used command
kubectl get pods
kubectl get deployments
kubectl get services
kubectl get all # all common resources
kubectl get pods -n production # in a specific namespace
kubectl get pods -A # across all namespaces
# Describe a resource β detailed info including recent events
# Essential when a Pod is failing to start
kubectl describe pod my-app-abc123
# View logs
kubectl logs my-app-abc123
kubectl logs -f my-app-abc123 # follow (live stream)
kubectl logs --previous my-app-abc123 # logs from a crashed container
# Open a shell inside a running container
kubectl exec -it my-app-abc123 -- sh
# Scale a deployment manually
kubectl scale deployment my-app --replicas=5
# Trigger a rolling restart (useful to pick up new ConfigMap values)
kubectl rollout restart deployment my-app
# Check rollout status
kubectl rollout status deployment my-app
# Roll back to the previous version
kubectl rollout undo deployment my-app
# Watch pods in real time (updates in place)
kubectl get pods -w
# Port-forward a service to your local machine for testing
# Access the app at localhost:8080 without exposing it publicly
kubectl port-forward svc/my-app-service 8080:80
# Delete a resource
kubectl delete pod my-app-abc123 # Deployment will replace it
kubectl delete -f deployment.yaml # delete from a file
Namespaces β Folders for Your Cluster
A namespace is a virtual cluster within a cluster. All resources (Pods, Services, Secrets)
exist within a namespace. By default, everything goes into the default namespace.
In real deployments, you use namespaces to separate concerns: production,
staging, monitoring, ingress-nginx.
Namespaces provide isolation β a Pod in the production namespace cannot
accidentally communicate with a Pod in staging unless you explicitly
configure it to. They also allow you to set resource quotas per namespace, limiting
how much CPU and memory a team's workloads can consume.
# Create a namespace
kubectl create namespace production
# Or via YAML (preferred for GitOps)
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
environment: production
Health Checks: Liveness and Readiness Probes
Kubernetes knows a container is running β but it does not automatically know if the application inside is healthy and ready to serve traffic. Two types of probes give Kubernetes that information.
Liveness Probe β "Is the App Alive?"
A liveness probe asks: is this application still working? If the probe fails repeatedly, Kubernetes restarts the container. This handles scenarios like a deadlock β the process is running but frozen and can never recover. Without a liveness probe, Kubernetes would never know to restart it.
Readiness Probe β "Is the App Ready for Traffic?"
A readiness probe asks: is this application ready to receive requests right now? If the probe fails, Kubernetes removes the Pod from the Service's load balancer. Traffic stops routing to it. This is crucial during startup (don't send traffic before the app has finished loading) and during overload (if the app is overwhelmed, take it out of rotation rather than making things worse).
containers:
- name: app
image: myapp:1.0
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 15 # wait 15s before first check (startup time)
periodSeconds: 20 # check every 20 seconds
failureThreshold: 3 # restart after 3 consecutive failures
readinessProbe:
httpGet:
path: /ready
port: 3000
initialDelaySeconds: 5 # check sooner β we want to start taking traffic fast
periodSeconds: 5
failureThreshold: 3 # remove from Service after 3 failures
Your application needs to expose these two endpoints. A /health endpoint
should return HTTP 200 as long as the process is alive and not deadlocked. A
/ready endpoint should return 200 only when the app has finished startup,
established database connections, and is genuinely ready to handle requests.
At Google's scale (where Kubernetes was born), hardware fails constantly. A server dies every few minutes somewhere in a datacenter of 100,000 machines. Kubernetes was designed from the ground up for this reality. When a node fails, Kubernetes detects that its Pods stopped reporting healthy, evicts them, and reschedules them on healthy nodes β automatically, within seconds. The engineers who designed Kubernetes built a system that treats hardware failure as a normal, everyday event.
Managed Kubernetes Services
Managing the Kubernetes control plane yourself is genuinely complex work. You have to keep the API server highly available, back up etcd, upgrade Kubernetes versions without downtime, and patch security vulnerabilities. Most companies outsource this to their cloud provider.
AWS EKS (Elastic Kubernetes Service) β AWS manages the control plane. You provision EC2 instances (or use Fargate for serverless nodes) as worker nodes. Deeply integrated with IAM, ALB, ECR, and other AWS services.
Google GKE (Google Kubernetes Engine) β Google invented Kubernetes and their managed service shows it. GKE Autopilot mode removes the need to manage nodes at all β you just deploy workloads and GKE handles the rest. Widely considered the most mature managed Kubernetes offering.
Azure AKS (Azure Kubernetes Service) β Microsoft's offering, well-integrated with Azure Active Directory, Azure Container Registry, and Azure Monitor. Popular in enterprise environments with existing Microsoft infrastructure.
Before touching cloud Kubernetes, practice locally with minikube or kind (Kubernetes
in Docker). Run minikube start and you have a single-node cluster on your
laptop in two minutes. Deploy manifests, break things, fix them β without paying cloud
costs. Once concepts feel familiar, managed services will make much more sense.
Chapter Summary
- Kubernetes orchestrates containers across clusters of machines, automatically healing crashes, scaling under load, and rolling out updates without downtime.
- The control plane (API server, etcd, scheduler, controllers) manages cluster state. Worker nodes (kubelet, kube-proxy, container runtime) run the actual workloads.
- Pods are the smallest unit. Deployments manage Pods with rolling updates. Services give Pods a stable network address. Ingress routes external HTTP traffic to Services.
- ConfigMaps hold non-sensitive configuration; Secrets hold sensitive data. Both are injected into containers as environment variables or mounted files.
- Liveness probes trigger container restarts when an app is stuck. Readiness probes remove Pods from load-balancing rotation when they are not ready for traffic.
- HorizontalPodAutoscaler automatically adjusts replica counts based on CPU or memory metrics β no human intervention needed for scaling under variable load.
- EKS, GKE, and AKS are managed Kubernetes services that handle the complex control plane so you can focus on deploying applications.