Kubernetes
A complete guide to Kubernetes (K8s): container orchestration at scale, Control Plane vs Worker Nodes, Pods, Deployments, Services, and self-healing.
Imagine you run the public transit system for a large city with 10,000 buses. Docker is like an individual bus: it has an engine, wheels, and seats, and it carries passengers reliably down the street. Now consider the bigger picture: Who decides which route each bus takes? Who replaces a bus if its engine breaks down on the highway? Who dispatches 200 extra buses when a major concert ends and thousands of people need a ride? Who manages traffic signals so buses do not collide? And how do you upgrade all 10,000 buses to newer models without halting public transit for even a minute? That coordination challenge is called Container Orchestration, and Kubernetes is the industry-standard platform built to solve it. Often abbreviated as K8s (representing the eight letters between 'K' and 's'), Kubernetes was originally designed by Google based on fifteen years of running their internal cluster system ('Borg'). Kubernetes manages thousands of containers across fleets of cloud servers, automating deployment, scaling, health recovery, and networking.
Definition
Kubernetes is an open-source container orchestration system that automates the deployment, scaling, networking, and self-healing of containerized applications across clusters of worker nodes.
Why It Matters
Running one or two containers on a developer's laptop with Docker is simple. But modern web platforms consist of dozens or hundreds of microservices running across dozens of cloud servers. What happens in the middle of the night if a physical server hosting your billing service suffers a hardware failure? Without an orchestrator, your service stays down until an engineer wakes up, logs into a cloud console, starts a new server, and restarts containers manually. With Kubernetes, the platform detects the server failure within seconds, finds another healthy node with available capacity, schedules replacement containers, reconfigures network routes, and restores traffic automatically.
How It Works
A Kubernetes cluster is organized into two main parts: The Control Plane (the cluster brain) and Worker Nodes (the compute muscle): 1. The Control Plane Components: • `kube-apiserver`: The central API gateway of the cluster. Every command (`kubectl`), controller, and node communicates through the API server. It handles authentication, permissions (RBAC), and validation. • `etcd`: A reliable distributed key-value store that holds the complete state of the cluster. It stores what you want running and what is currently running. • `kube-scheduler`: Looks for newly created Pods that need a home and assigns them to the best available Worker Node based on memory, CPU, and placement rules. • `kube-controller-manager`: Runs background loops (like the Deployment and Node controllers) that constantly compare the 'Desired State' declared in your YAML files with the 'Actual State' running on servers, taking action to keep them in sync. 2. Worker Node Components: • `kubelet`: The agent running on each worker node that talks to the Control Plane and ensures the containers described in your Pods are running and healthy. • `kube-proxy`: A network proxy on each node that maintains network rules to route incoming traffic to the right Pods. • Container Runtime: The underlying engine (such as containerd) that actually downloads images and runs containers. 3. Core Kubernetes Objects: • Pod: The smallest deployable unit in Kubernetes. A Pod wraps one or more related containers that share the same network IP address and storage volumes. • Deployment: A controller that manages Pod replicas, handling rolling updates and rollbacks automatically. • Service: An abstraction that provides a stable, permanent IP address and internal DNS name to direct traffic across dynamic, temporary Pods. • Ingress: An intelligent gateway that routes external HTTP and HTTPS traffic from outside the cluster to internal Services based on domain names and URL paths.
Kubernetes Cluster Architecture: Control Plane and Worker Nodes
Key Points
- Kubernetes is built on Desired State: you declare what you want running, and controllers work continuously to make reality match.
- A Pod is the basic unit of deployment; containers almost always run inside a Pod rather than standalone.
- Pods are temporary and can be replaced; Services provide stable IP addresses and DNS names to reach them.
- Self-Healing: Kubernetes automatically restarts crashed containers and reschedules pods away from failing servers.
- Always configure Liveness and Readiness probes so traffic is routed only to healthy, initialized containers.
- `etcd` holds the entire cluster state: taking regular backups of etcd is critical for disaster recovery.
Steps
Write a Declarative Deployment Manifest
Create a YAML file specifying the container image, replica count, environment variables, resource limits, and health checks.
Create a Service for Stable Networking
Define a `ClusterIP` or `LoadBalancer` Service using label selectors (`app: order-service`) to balance traffic across your Pods.
Apply the Manifest to the Cluster
Send your configuration to Kubernetes with `kubectl apply -f deployment.yaml`.
Monitor Pod Status and Logs
Check that pods are running with `kubectl get pods` and view application output using `kubectl logs -l app=order-service -f`.
Perform Zero-Downtime Updates
Update the image tag in your YAML file and reapply it; Kubernetes rolls out new pods while keeping existing pods running until the new ones are ready.
Examples
The Symphony Orchestra Conductor Analogy
Docker containers are like individual musicians: violinists, trumpeters, and flutists. But fifty musicians playing together without coordination produces noise. Kubernetes is the Orchestra Conductor: keeping time, cueing sections when to play, adjusting volume, and smoothly calling in an understudy if a musician needs to step away.
Real-World Examples
Global Scaling During Traffic Surges
When popular mobile games or online services experience sudden global surges in player activity, traffic can exceed initial projections by dozens of times. By running on managed Kubernetes services like Google Kubernetes Engine (GKE) or AWS EKS, platforms scale across thousands of nodes and hundreds of thousands of pods automatically, avoiding outages that would otherwise affect traditional server setups.
Technical Examples
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-service
namespace: production
labels:
app.kubernetes.io/name: order-service
spec:
replicas: 3
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # Allow 1 extra pod during rollout
maxUnavailable: 0 # Zero downtime: keep at least 3 pods available at all times
selector:
matchLabels:
app: order-service
template:
metadata:
labels:
app: order-service
spec:
securityContext:
runAsNonRoot: true
runAsUser: 10001
containers:
- name: web
image: ghcr.io/myorg/order-service:v2.4.1
ports:
- containerPort: 8080
name: http
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
# Readiness Probe: Determines when the pod is ready to accept user traffic
readinessProbe:
httpGet:
path: /healthz/ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 2
# Liveness Probe: Detects if the application is frozen and needs a restart
livenessProbe:
httpGet:
path: /healthz/live
port: 8080
initialDelaySeconds: 15
periodSeconds: 10
failureThreshold: 3
---
apiVersion: v1
kind: Service
metadata:
name: order-service
namespace: production
spec:
type: ClusterIP
selector:
app: order-service
ports:
- name: http
port: 80
targetPort: 8080Kubernetes (K8s) vs Docker Compose
| Aspect | Kubernetes (K8s) | Docker Compose |
|---|---|---|
| Primary Target | Multi-node production cloud clusters | Single-node local development environments |
| Self-Healing | Reschedules pods across healthy servers automatically | Restarts crashed containers on your local computer only |
| Autoscaling | Automatic horizontal and vertical scaling (HPA/VPA) | Manual replica configuration in local files |
| Rolling Updates | Built-in zero-downtime rolling and canary rollouts | Recreates containers, usually causing brief interruption |
| Operational Complexity | Higher: requires cluster administration knowledge | Very low: simple single-file setup for local testing |
How the Control Loop Works
Advantages
- High Availability and Self-Healing: Automatically restarts failed containers and moves workloads away from unhealthy hardware.
- Zero-Downtime Releases: Rolling updates replace containers smoothly without interrupting user sessions.
- Resource Optimization: Distributes containers efficiently across worker nodes to maximize memory and CPU usage.
- Cloud Flexibility: Runs consistently on AWS (EKS), Google Cloud (GKE), Azure (AKS), or on-premises servers.
Limitations
- Operational Learning Curve: Managing clusters, network plugins, and storage interfaces requires specialized knowledge.
- Can Be Overkill for Simple Sites: A small website with modest traffic is often simpler and cheaper to run on PaaS platforms.
Interview Questions
What happens behind the scenes when you run 'kubectl apply -f deployment.yaml'?
1. `kubectl` sends the manifest to `kube-apiserver`. 2. The API server authenticates, checks permissions (RBAC), validates the manifest, and saves the desired state in `etcd`. 3. The `Deployment Controller` notices the new deployment and creates a `ReplicaSet`. 4. The `ReplicaSet Controller` creates the required `Pods`. 5. The `kube-scheduler` sees the new Pods, checks worker node capacity, and assigns each Pod to an appropriate node. 6. The `kubelet` on the chosen node detects the assignment and directs the container runtime (like containerd) to pull the image, start the container, and begin running health checks.
Practice Questions
- Set up a local test cluster using Minikube or Kind and deploy a simple NGINX deployment with 3 replicas.
- Simulate a container failure by deleting a running pod with `kubectl delete pod <pod-name>` and watch how the ReplicaSet automatically recreates it.
