5 Dec 2026 · 99 min read
Kubernetes, from Zero to Production
Every concept, edge case, YAML field and diagram you need, from theory to a real deployment of Next.js and Java on AWS EKS.
1. Why is Kubernetes Needed?#
The problem before Kubernetes#
You've built your app and containerised it with Docker. On a single server, docker run works fine. But production brings problems Docker alone cannot solve:
What Kubernetes gives you#
- 🔄 Self-healing: Container crashes → K8s detects within seconds → restarts it automatically. Node dies → all its pods get rescheduled to healthy nodes. No human intervention needed.
- 📈 Auto-scaling: HorizontalPodAutoscaler watches CPU/memory/custom metrics. Traffic doubles → K8s spins up more pods. Traffic drops → K8s removes excess pods. You can even auto-scale the nodes themselves.
- 🚀 Rolling updates: Deploy v2 while v1 is running. K8s creates new pods one by one, health-checks them, then kills old pods. Zero user-facing downtime. If v2 is broken, K8s stops the rollout.
- 🔍 Service discovery & DNS: Every Service gets a DNS name. Your Next.js app finds the Java backend at
java-api-svc:8080— no hardcoded IPs, no config changes when pods move. - 🔐 Secret management: DB passwords and API keys stored as encrypted Secrets, injected into pods as environment variables or mounted files. Never hardcoded in images.
- 📦 Bin-packing: The Scheduler fits pods onto nodes like Tetris — maximising resource usage. A cluster of 10 nodes can run hundreds of pods efficiently.
- ↩️ Rollback: Deployed a bug? One command:
kubectl rollout undo. K8s reverts to the previous version instantly. It keeps revision history. - 🌐 Multi-cloud / Hybrid: Same YAML files work on AWS, GCP, Azure, bare metal. Vendor-neutral. Your team learns one system, deploys anywhere.
- Imperative: "Create a pod, then create another pod, then create a third pod." You give step-by-step commands. If something fails mid-way, you're left in an unknown state.
- Declarative: "There should be 3 pods." K8s figures out the current state, diffs it against desired state, and takes whatever action is needed. Always converges to the right state.
2. Complete K8s Architecture#
A Kubernetes cluster has two halves: the Control Plane (the brain that makes decisions) and Worker Nodes (the machines that run your containers). Every single interaction goes through the API Server — it's the only component that talks to etcd.
3. Pods — The Atomic Unit#
A Pod is not a container. It's a wrapper around one or more containers that share a network namespace, IP address, and optionally volumes. It's the smallest thing Kubernetes can schedule.
Pod Lifecycle States#
Init Containers#
Containers that run before the main containers start. They run sequentially, and the main containers don't start until all init containers complete. Use cases: wait for a database to be ready, clone a git repo, populate a shared volume, run schema migrations.
4. Nodes — The Machines#
A Node is a physical server or virtual machine (like an EC2 instance) that runs your pods. Each node has three mandatory components plus optional add-ons.
Taints and Tolerations#
Nodes can have taints that repel pods. Only pods with matching tolerations can be scheduled on tainted nodes. This keeps certain nodes reserved (e.g., GPU nodes only run ML workloads).
kubectl taint nodes node-gpu-01 gpu=true:NoSchedule
# Only pods with this toleration get scheduled on it:
tolerations:
- key: "gpu"
operator: "Equal"
value: "true"
effect: "NoSchedule"
Node Affinity vs Node Selector#
| Feature | nodeSelector | nodeAffinity |
|---|---|---|
| Complexity | Simple key-value match | Rich expressions (In, NotIn, Exists, Gt, Lt) |
| Soft preference | No (hard requirement only) | Yes — preferredDuringScheduling |
| Use case | "Run on SSD nodes" | "Prefer zone-a, but zone-b is OK" |
5. Control Plane — The Brain#
What happens inside the API Server (request pipeline)#
- RBAC: Role-Based Access Control. Defines who (ServiceAccount, User, Group) can do what (get, list, create, delete) on which resources (pods, services, secrets) in which namespaces. Example: developers can read pods in "staging" but only admins can delete pods in "production."
- Admission Controller: Plugins that intercept requests AFTER authentication/authorization but BEFORE persistence. Mutating webhooks can modify requests (inject sidecar containers). Validating webhooks can reject requests (block images not from your registry). This is how Istio auto-injects Envoy sidecars.
5b. What is a Master Node?#
Master Node is the informal name for any node that runs the Control Plane components. In Kubernetes terminology, the official name is control plane node (the term "master" was deprecated in the naming conventions). It is a regular machine (physical or VM) — but instead of running your application pods, it runs the cluster's brain: API Server, Scheduler, Controller Manager, and usually an etcd member.
Why master nodes don't run your application pods#
Master nodes are tainted by default with node-role.kubernetes.io/control-plane:NoSchedule. This taint repels regular pods — keeping the control plane isolated so a runaway application can't consume all CPU/memory and crash the brain of the cluster. You can remove this taint (common on small single-node dev clusters like Minikube), but in production, keep it.
Master Node in managed Kubernetes (EKS, GKE, AKS)#
On AWS EKS, you never see or SSH into the master nodes. AWS manages them entirely — they run across 3 AZs, are auto-healed, and etcd is backed up. The kubectl get nodes command only shows your worker nodes. The master is invisible to you, exposed only through the API Server endpoint (a URL like https://ABC123.gr7.ap-south-1.eks.amazonaws.com).
| Aspect | Self-managed (kubeadm) | Managed (EKS/GKE/AKS) |
|---|---|---|
| Master visibility | You see master nodes in kubectl get nodes |
Master nodes are hidden — you only see the API endpoint |
| Master maintenance | You patch, upgrade, backup etcd yourself | Cloud provider handles everything automatically |
| Cost | You pay for the master VMs | EKS charges $0.10/hour for the control plane (no VM cost) |
| HA setup | You provision 3+ masters yourself, configure etcd cluster | Built-in: 3 masters across 3 AZs by default |
| etcd | Runs on master nodes, you manage backups | Managed etcd, automatic backups every 5 minutes |
6. API Server — In Detail#
The kube-apiserver is the front door to the entire cluster. Every single interaction — from kubectl commands to kubelet status reports to controller watch streams — is a REST API call to this server.
Key responsibilities#
It authenticates every request (via certificates, tokens, or OIDC), authorises it (RBAC), runs admission controllers (mutating/validating webhooks), validates the object schema, and then persists the object to etcd. It also serves the watch API — long-lived streaming connections where components subscribe to changes ("tell me whenever a new pod is created").
7. Scheduler — Deep Dive#
8. Services — Stable Networking#
Pods get random IPs and die constantly. A Service creates a stable virtual IP (ClusterIP) + DNS name that load-balances traffic across a set of pods matched by label selector.
All four Service types compared#
| Type | Scope | How it works | Use case |
|---|---|---|---|
| ClusterIP | Internal only | Virtual IP inside the cluster. Not reachable from outside. | Backend APIs, databases, internal microservices |
| NodePort | External via node IP | Opens port 30000-32767 on every node. Traffic: NodeIP:NodePort → Service → Pod. | Dev/test, simple exposures. Not production-grade. |
| LoadBalancer | External via cloud LB | Provisions a cloud load balancer (AWS ALB/NLB). Gets a public DNS. | Exposing a single service publicly. Costs $$$ per LB. |
| ExternalName | DNS alias | Maps a Service name to an external DNS name (CNAME). No proxying. | Pointing to RDS or external APIs via K8s DNS. |
- Endpoints: The list of Pod IPs that a Service routes to. Kubernetes automatically updates this list when pods are created/destroyed. The Endpoints controller watches for pod changes and updates the Endpoints object. You can see them with
kubectl get endpoints java-api-svc. - Headless Service: A Service with
clusterIP: None. Instead of a virtual IP, DNS returns the actual pod IPs directly. Used for stateful workloads (databases) where clients need to connect to specific pods (e.g. Kafka broker 0, broker 1).
9. Deployments & the YAML File#
The hierarchy#
Rolling Update — visualized#
Fully annotated deployment.yaml#
apiVersion: apps/v1 # API group. apps/v1 is the stable Deployment API.
kind: Deployment # Resource type.
metadata:
name: java-api # Unique name within the namespace.
namespace: production # Which namespace (default if omitted).
labels:
app: java-api # Labels on the Deployment itself (for queries).
version: v1.4.0
spec:
replicas: 3 # Desired number of identical pods.
revisionHistoryLimit: 5 # Keep last 5 ReplicaSets for rollback.
selector:
matchLabels:
app: java-api # MUST match template labels. Immutable after creation.
strategy:
type: RollingUpdate # Other option: Recreate (kill all, then create all).
rollingUpdate:
maxUnavailable: 1 # Max pods that can be down during update.
maxSurge: 1 # Max extra pods above replicas during update.
template: # ── Pod template starts here ──
metadata:
labels:
app: java-api # These labels are on every Pod created.
annotations:
prometheus.io/scrape: "true" # Prometheus discovers this pod.
prometheus.io/port: "8080"
spec:
serviceAccountName: java-api-sa # RBAC identity for this pod.
terminationGracePeriodSeconds: 30 # Time to finish requests before SIGKILL.
initContainers: # Runs BEFORE main containers.
- name: wait-for-db
image: busybox:1.36
command: ['sh', '-c',
'until nc -z postgres-svc 5432; do echo waiting...; sleep 2; done']
containers:
- name: java-api
image: 123456789.dkr.ecr.ap-south-1.amazonaws.com/java-api:v1.4.0
ports:
- containerPort: 8080
protocol: TCP
resources:
requests: # GUARANTEED minimum. Scheduler uses this.
cpu: "500m" # 500 millicores = 0.5 CPU core.
memory: "512Mi" # 512 mebibytes.
limits: # MAXIMUM allowed. Exceeding = throttle (CPU) or OOMKill (memory).
cpu: "1000m"
memory: "1Gi"
env:
- name: SPRING_PROFILES_ACTIVE
value: "production"
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-credentials
key: password
- name: DB_HOST
valueFrom:
configMapKeyRef:
name: app-config
key: db_host
livenessProbe: # Is the container alive? Failure = restart container.
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 30 # Wait before first check (JVM startup).
periodSeconds: 10 # Check every 10s.
failureThreshold: 3 # 3 consecutive failures = restart.
readinessProbe: # Is it ready for traffic? Failure = remove from Service endpoints.
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
failureThreshold: 3
startupProbe: # For slow-starting apps. Disables liveness/readiness until it passes.
httpGet:
path: /actuator/health
port: 8080
failureThreshold: 30 # 30 × 10s = up to 5 min to start.
periodSeconds: 10
volumeMounts:
- name: config-volume
mountPath: /app/config
readOnly: true
volumes:
- name: config-volume
configMap:
name: java-api-config
- requests: The guaranteed minimum resources. The Scheduler uses this to find a node with enough capacity. If you request 500m CPU and the node has 500m free, the pod can be scheduled. Your pod always gets at least this much.
- limits: The maximum a container can use. If it tries to use more CPU, it gets throttled. If it uses more memory, it gets OOMKilled. Set limits to prevent a runaway container from starving others on the same node.
- livenessProbe: Checks if the container is alive. If this fails
failureThresholdtimes in a row, kubelet kills and restarts the container. Use this to catch deadlocks where the process is alive but stuck. - readinessProbe: Checks if the container is ready to receive traffic. If this fails, the pod is removed from Service endpoints — it stays alive but stops getting traffic. Use this during startup and when the app needs to temporarily drain (e.g., waiting for cache warmup).
- startupProbe: For apps that take a long time to start (JVM, .NET). Until this probe passes, liveness and readiness probes are paused. Without it, the liveness probe might kill a container that's still booting.
9b. pod.yaml vs service.yaml vs deployment.yaml — Do You Need All of Them?#
This is one of the most common questions. Kubernetes has several resource types, each with its own YAML file. Let's look at what each one does, when you need it, and whether you can skip some.
The three core YAML files#
What a standalone pod.yaml looks like (for learning only)#
apiVersion: v1
kind: Pod # Just a bare pod — no controller manages it
metadata:
name: java-api-test # Fixed name. Can't have 2 with same name.
labels:
app: java-api
spec:
containers:
- name: java-api
image: 123456789.dkr.ecr.ap-south-1.amazonaws.com/java-api:v1.4.0
ports:
- containerPort: 8080
resources:
requests:
cpu: "500m"
memory: "512Mi"
# ⚠️ If this pod crashes, NOBODY restarts it.
# ⚠️ You can't scale it — it's always just 1.
# ⚠️ You can't do rolling updates.
# ⚠️ This is why you use a Deployment instead.
What a service.yaml looks like#
apiVersion: v1
kind: Service
metadata:
name: java-api-svc # This becomes the DNS name:
namespace: production # java-api-svc.production.svc.cluster.local
labels:
app: java-api # Labels on the Service itself (for queries)
spec:
type: ClusterIP # ClusterIP | NodePort | LoadBalancer | ExternalName
selector:
app: java-api # ← MUST match the labels on your Pods
# (from deployment.yaml → spec.template.metadata.labels)
ports:
- name: http # Name is required when you have multiple ports
port: 8080 # Port the Service listens on (what clients use)
targetPort: 8080 # Port on the container (containerPort in pod spec)
protocol: TCP # TCP (default) or UDP
# For NodePort, you'd add:
# - nodePort: 30080 # External port on every node (30000-32767)
sessionAffinity: None # None (round-robin) or ClientIP (sticky sessions)
The answer: Can one file do everything?#
apiVersion: apps/v1
kind: Deployment
metadata:
name: java-api
namespace: production
spec:
replicas: 3
selector:
matchLabels:
app: java-api
template:
metadata:
labels:
app: java-api
spec:
containers:
- name: java-api
image: 123456789.dkr.ecr.ap-south-1.amazonaws.com/java-api:v1.4.0
ports:
- containerPort: 8080
resources:
requests: { cpu: "500m", memory: "512Mi" }
limits: { cpu: "1000m", memory: "1Gi" }
--- # ← YAML document separator
apiVersion: v1
kind: Service
metadata:
name: java-api-svc
namespace: production
spec:
type: ClusterIP
selector:
app: java-api # ← matches pod labels above
ports:
- port: 8080
targetPort: 8080
--- # ← another document separator
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: java-api-ingress
namespace: production
annotations:
kubernetes.io/ingress.class: alb
spec:
rules:
- host: api.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: java-api-svc # ← references the Service above
port:
number: 8080
Single file vs multiple files — which is better?#
| Approach | Pros | Cons | When to use |
|---|---|---|---|
| Single file | Simple, one kubectl apply, easy to review |
Hard to manage when it grows to 500+ lines. Can't version resources independently. | Small apps, quick prototyping, learning |
| Separate files | Each resource has its own lifecycle. Clear Git diffs. Easy to reuse. | More files to manage. Must apply a directory: kubectl apply -f k8s/ |
Production. Standard practice. |
| Helm chart | Templated YAML with variables. Package multiple resources as one versioned unit. | Learning curve. Abstracts away raw YAML. | Teams, reusable infra, complex apps |
| Kustomize | Overlay system: base YAML + environment patches. Built into kubectl. | Can't do complex logic (loops, conditionals). | Multi-environment: dev/staging/prod overlays |
k8s/
├── base/
│ ├── deployment.yaml # Deployment (includes pod template)
│ ├── service.yaml # Service
│ ├── ingress.yaml # Ingress rules
│ ├── configmap.yaml # Non-sensitive config
│ ├── hpa.yaml # Autoscaling rules
│ └── kustomization.yaml # Kustomize base
├── overlays/
│ ├── staging/
│ │ ├── kustomization.yaml # replicas: 1, staging image tag
│ │ └── patch-replicas.yaml
│ └── production/
│ ├── kustomization.yaml # replicas: 3, prod image tag, resource limits
│ └── patch-replicas.yaml
└── secrets/ # Not in Git! Managed via Sealed Secrets or external
└── db-credentials.yaml
# Deploy to staging:
kubectl apply -k k8s/overlays/staging/
# Deploy to production:
kubectl apply -k k8s/overlays/production/
Which resources are REQUIRED for a working app?#
10. High Availability — When the Control Plane Fails#
11. Cloud Load Balancer#
When you create a Service with type: LoadBalancer, the Cloud Controller Manager talks to AWS and provisions a real load balancer. This gives your service a public-facing endpoint.
| AWS LB Type | OSI Layer | When to use | K8s annotation |
|---|---|---|---|
| ALB | Layer 7 (HTTP) | HTTP/HTTPS routing, path-based rules, WebSocket, gRPC. Best for web apps. | alb via Ingress |
| NLB | Layer 4 (TCP/UDP) | Raw TCP, ultra-low latency, static IPs. Best for gRPC, databases, gaming. | service.beta.kubernetes.io/aws-load-balancer-type: nlb |
| CLB | Layer 4/7 (legacy) | Don't use. Old generation. Default if you don't specify. | Default (avoid) |
12. Ingress — The Smart Router#
Ingress is a K8s object that defines HTTP routing rules. It needs an Ingress Controller (a pod running nginx, Traefik, or the AWS LB Controller) to actually implement those rules.
Complete Ingress YAML — every field explained#
apiVersion: networking.k8s.io/v1 # Stable Ingress API (since K8s 1.19)
kind: Ingress
metadata:
name: app-ingress
namespace: production
annotations:
# ── Which Ingress Controller handles this? ──
kubernetes.io/ingress.class: alb # Use AWS ALB (could be "nginx" for nginx-ingress)
# ── AWS ALB-specific configuration ──
alb.ingress.kubernetes.io/scheme: internet-facing # internet-facing (public) or internal (private)
alb.ingress.kubernetes.io/target-type: ip # "ip" = route to pod IPs directly (best for EKS)
# "instance" = route to node IPs via NodePort
alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:ap-south-1:123456789:certificate/abc-def
# ACM cert for HTTPS/TLS
alb.ingress.kubernetes.io/listen-ports: '[{"HTTPS":443}]' # Only listen on 443
alb.ingress.kubernetes.io/ssl-redirect: "443" # Redirect HTTP→HTTPS
alb.ingress.kubernetes.io/group.name: my-app # Group multiple Ingress into ONE ALB
alb.ingress.kubernetes.io/healthcheck-path: /health # ALB health check path
alb.ingress.kubernetes.io/healthcheck-interval-seconds: "15"
alb.ingress.kubernetes.io/success-codes: "200,301"
alb.ingress.kubernetes.io/wafv2-acl-arn: arn:aws:wafv2:... # Attach WAF for DDoS/bot protection
spec:
# ── Default backend (when no rule matches) ──
defaultBackend:
service:
name: default-404-svc # Custom 404 page service
port:
number: 80
# ── TLS configuration (for nginx-ingress; ALB uses annotation above) ──
# tls:
# - hosts:
# - app.example.com
# secretName: tls-secret # K8s Secret containing TLS cert+key
# ── Routing rules ──
rules:
- host: app.example.com # Match this hostname (Host header)
http:
paths:
- path: /api # Match URL path prefix
pathType: Prefix # Prefix = "/api" matches "/api", "/api/users", "/api/v1/health"
# Exact = "/api" matches ONLY "/api", not "/api/users"
backend:
service:
name: java-api-svc # Route to this K8s Service
port:
number: 8080 # On this port
- path: / # Catch-all for everything else
pathType: Prefix
backend:
service:
name: nextjs-svc
port:
number: 3000
- host: admin.example.com # Different hostname → different service
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: admin-svc
port:
number: 3001
- pathType: Prefix: Matches the URL path prefix.
/apimatches/api,/api/,/api/users,/api/v1/data. The most common choice. Longest prefix wins when multiple rules overlap. - pathType: Exact: Matches the URL path exactly.
/apimatches only/apiand nothing else — not/api/, not/api/users. Use for specific endpoints like health checks. - pathType: ImplementationSpecific: Behaviour depends on the Ingress Controller. Avoid this — use Prefix or Exact for predictable behaviour across controllers.
- group.name annotation: Multiple Ingress resources with the same
group.nameshare a single ALB. This lets different teams define their own Ingress YAML files that all route through one load balancer — saving cost.
12b. How to Trace Where www.xyz.com Goes — Finding the IP#
Given a URL like www.xyz.com, here's exactly how to trace the full path from domain name to the actual Kubernetes pod, and how to find every IP involved.
Commands to trace every hop#
# ── 1. Find the IP behind the domain (from your laptop) ──
nslookup www.xyz.com
# → Non-authoritative answer:
# → www.xyz.com canonical name = k8s-prod-abc123.ap-south-1.elb.amazonaws.com
# → Address: 52.66.148.23 ← This is the ALB's public IP
# → Address: 13.234.76.112 ← ALB has one IP per AZ
dig www.xyz.com
# → ;; ANSWER SECTION:
# → www.xyz.com. 60 IN CNAME k8s-prod-abc123.ap-south-1.elb.amazonaws.com.
# → k8s-prod-abc123.ap-south-1.elb.amazonaws.com. 60 IN A 52.66.148.23
# ── 2. Find which Ingress owns this domain (from kubectl) ──
kubectl get ingress -A
# → NAMESPACE NAME CLASS HOSTS ADDRESS PORTS AGE
# → production app-ingress alb www.xyz.com k8s-prod-abc123.ap-south-1.elb.amazonaws 80,443 30d
# The ADDRESS column shows the ALB DNS name — same as what nslookup returned.
# So yes: the IP you resolve from www.xyz.com IS the ALB that the Ingress created.
kubectl describe ingress app-ingress -n production
# → Rules:
# → Host Path Backends
# → ---- ---- --------
# → www.xyz.com
# → /api java-api-svc:8080 (10.244.1.5:8080,10.244.2.9:8080)
# → / nextjs-svc:3000 (10.244.1.12:3000,10.244.3.4:3000)
# → ← Shows exactly which pods are behind each path!
# ── 3. Find the Service and its endpoints ──
kubectl get svc java-api-svc -n production
# → NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S)
# → java-api-svc ClusterIP 10.96.0.14 <none> 8080/TCP
kubectl get endpoints java-api-svc -n production
# → NAME ENDPOINTS AGE
# → java-api-svc 10.244.1.5:8080,10.244.2.9:8080 30d
# → ← These are the actual Pod IPs receiving traffic
# ── 4. Find exactly which node and pod ──
kubectl get pods -n production -l app=java-api -o wide
# → NAME READY STATUS IP NODE
# → java-api-abc123-d4e5f 1/1 Running 10.244.1.5 ip-10-0-1-45.ec2.internal
# → java-api-abc123-g6h7i 1/1 Running 10.244.2.9 ip-10-0-2-78.ec2.internal
# → Now you know the exact pod IP, the node it's on, and its status.
# ── 5. Test the full chain from outside ──
curl -v https://www.xyz.com/api/health
# → * Connected to www.xyz.com (52.66.148.23) port 443 ← ALB IP
# → * TLS handshake... certificate: *.xyz.com ← ACM cert on ALB
# → < HTTP/2 200 ← Response from pod
# → {"status":"UP"}
What exactly is "the Ingress IP"?#
13. Persistent Storage#
- ReadWriteOnce (RWO): Volume can be mounted as read-write by a single node. Standard for EBS. Most databases use this.
- ReadWriteMany (RWX): Volume can be mounted as read-write by multiple nodes simultaneously. Required when multiple pods on different nodes need to write to the same volume. Use EFS (NFS) on AWS.
- emptyDir: Temporary volume that exists for the lifetime of a pod. Created when the pod is assigned to a node, deleted when the pod is removed. Used for scratch space and sharing data between containers in the same pod.
- Reclaim Policy:
Delete(default): when the PVC is deleted, the PV and the underlying EBS volume are also deleted.Retain: PV is kept after PVC deletion for manual recovery. Use Retain for production databases.
14. Namespaces#
Namespaces are virtual clusters inside your physical cluster. They provide isolation for teams, environments, or projects.
default # Where resources go if you don't specify a namespace
kube-system # K8s system components (CoreDNS, kube-proxy, metrics-server)
kube-public # Publicly readable, cluster info
production # Your production workloads
staging # Your staging workloads
monitoring # Prometheus, Grafana, alertmanager
Namespaces let you set ResourceQuotas (max 10 pods, max 4Gi memory in this namespace) and LimitRanges (default resource limits for pods). This prevents one team from consuming all cluster resources.
15. ConfigMaps & Secrets#
| ConfigMap | Secret | |
|---|---|---|
| Stores | Non-sensitive config (DB hostnames, feature flags, config files) | Sensitive data (passwords, API keys, TLS certs) |
| Encoding | Plain text | Base64 encoded (NOT encrypted by default!) |
| Max size | 1 MB | 1 MB |
| Injection | Env vars or volume mount | Env vars or volume mount |
| Production | Fine as-is | Enable encryption at rest + use AWS Secrets Manager CSI driver |
16. Autoscaling#
17. K8s Networking Model#
Kubernetes has three fundamental networking rules that every CNI plugin (Calico, Cilium, AWS VPC CNI) must implement:
- CNI Plugin: Container Network Interface. The plugin that creates the pod network. On AWS EKS, the VPC CNI gives each pod a real VPC IP from your subnet — meaning pods are directly routable from other AWS services (RDS, Lambda) without extra hops.
- NetworkPolicy: K8s firewall rules. By default, all pods can talk to all pods. A NetworkPolicy selects pods by labels and defines which ingress/egress traffic is allowed. Example: "only pods with label
app=nextjscan reach pods with labelapp=java-apion port 8080."
18. The Reconciliation Loop — How K8s Self-Heals#
18b. AWS Infrastructure — Every Term in Layman Terms#
Before we deploy, you need to understand the AWS building blocks. Here's every service explained as if you've never touched AWS — then we'll wire them all together with real request-flow diagrams.
The AWS glossary you actually need#
Each term explained in plain language#
- DNS Table Lookup: DNS (Domain Name System) is the internet's phone book. When you type
www.xyz.com, your browser doesn't know where that is — it asks a DNS server "what IP address does www.xyz.com live at?" The DNS server looks up its records table and replies with an IP like52.66.148.23. That table has rows like:www.xyz.com → A → 52.66.148.23(A record = an IPv4 address) orwww.xyz.com → CNAME → some-lb.elb.amazonaws.com(CNAME = an alias to another domain). Route 53 is AWS's DNS service where you manage this table. Every request to your website starts with a DNS lookup — it's always step 1. - CNAME: CNAME stands for "Canonical Name" — it's a DNS record type that says "this domain is actually an alias for that other domain." Example:
www.xyz.com → CNAME → k8s-prod-abc.elb.amazonaws.com. The browser sees www.xyz.com, DNS says "actually, go ask for k8s-prod-abc.elb.amazonaws.com", then that resolves to an actual IP. CNAMEs are how you point your pretty domain to an ugly AWS load balancer URL. Alias records (Route 53-specific) work like CNAMEs but faster and free for AWS resources — always prefer them when pointing to ALBs, CloudFront, or S3. - S3 Bucket: S3 (Simple Storage Service) is infinite, cheap cloud file storage. A "bucket" is a top-level folder with a globally unique name (like
my-app-static-assets). You put any file in it — images, videos, CSS, JS bundles, database backups, logs. Key features: (1) 99.999999999% durability (11 nines — you'll never lose a file), (2) serves files via HTTP, (3) can host a static website directly, (4) pairs with CloudFront for global CDN delivery. Think of it as Google Drive, but for your application, accessible via API or URL. - EKS: Elastic Kubernetes Service — AWS's managed Kubernetes. Instead of setting up master nodes, etcd, and the control plane yourself (which takes days and requires deep expertise), EKS does it in 15 minutes. AWS runs and heals the control plane across 3 AZs. You just provide worker nodes (EC2 instances) and deploy your YAML files. Cost: $0.10/hour for the control plane + whatever EC2 instances you use.
- ES / OpenSearch: Originally called Elasticsearch (ES), AWS renamed it to OpenSearch Service. It's a search and analytics engine. You feed it data (logs, product catalogs, articles), and it lets you search through millions of documents in milliseconds. Two main uses: (1) the search bar on your website ("search for products containing 'wireless headphones'") and (2) centralized logging (ship all your pod logs here, query them in Kibana/OpenSearch Dashboards). Think of it as Google search, but for your own data.
- EC2: Elastic Compute Cloud — a virtual machine (server) that you rent by the hour. You choose the size: t3.micro (1 vCPU, 1 GB RAM, ~$8/month) up to m5.24xlarge (96 vCPU, 384 GB RAM). You pick the OS (Ubuntu, Amazon Linux), and it boots in under a minute. In the K8s context, your EKS worker nodes are EC2 instances. K8s pods run inside containers, containers run on these EC2 machines. Think of EC2 as renting a computer in Amazon's data centre.
- CloudFront: AWS's Content Delivery Network (CDN). It caches your static files (JS, CSS, images, fonts) at 400+ edge locations worldwide. A user in Mumbai gets your JS file from the Mumbai edge, not from your server in Virginia — cutting load time from 400ms to 20ms. It sits in front of either: (1) an S3 bucket (for static assets) or (2) your ALB (for the whole app). Also handles HTTPS, DDoS protection (Shield), and can compress files automatically. Think of it as a global cache layer.
- K8s (Kubernetes): An open-source container orchestration system. Not an AWS service — it runs on top of AWS (via EKS), Google Cloud (GKE), Azure (AKS), or your own servers. K8s takes your Docker containers and figures out: which machine to run them on, how many copies, what to do when one crashes, how to roll out updates without downtime. You tell it "I want 3 copies of my Java API always running" and it makes that happen forever.
K8sis shorthand: K, then 8 letters (ubernete), then s.
Extra terms you'll encounter#
- ALB (Application Load Balancer): Layer 7 (HTTP) load balancer. It reads the URL path and hostname to decide where to send traffic. When K8s creates an Ingress, the ALB controller provisions one of these. It's the "front door" that has a public IP and distributes traffic to your pods.
- NLB (Network Load Balancer): Layer 4 (TCP) load balancer. Doesn't understand HTTP — just forwards raw TCP packets. Ultra-low latency, supports static IPs. Use for gRPC, databases, or when you need a fixed IP.
- VPC (Virtual Private Cloud): Your own private network inside AWS. All your EC2 instances, RDS databases, and ElastiCache nodes live inside a VPC. It has subnets (public for ALBs, private for pods/databases), route tables, and NAT gateways. Think of it as your own private data centre floor inside Amazon's building.
- AZ (Availability Zone): A physically separate data centre within a region.
ap-south-1a,ap-south-1b,ap-south-1care three AZs in Mumbai. They have independent power and networking. Spreading your nodes across 3 AZs means if one data centre has a fire, your app keeps running. - ECR (Elastic Container Registry): AWS's private Docker image registry. You push your Docker images here, and EKS pulls them when creating pods. Like Docker Hub but private, integrated with IAM permissions, and in the same region as your cluster (fast pulls).
- ACM (AWS Certificate Manager): Provides free TLS/SSL certificates for your domains. Attach them to ALBs or CloudFront. Auto-renews. No more manually managing certificate files.
- IAM (Identity and Access Management): AWS's permission system. Defines who can do what. "This EKS pod can read from S3 bucket X but nothing else." Every AWS interaction is authorized through IAM. IRSA (IAM Roles for Service Accounts) bridges K8s service accounts to IAM roles.
Scenario 1: You have a server that handles GET /greet — how does a request reach it?#
Let's say you have a simple Java (or Node) server with one endpoint: GET /greet returns {"message": "Hello!"}. It's running as a containerised K8s pod on AWS EKS. Here's every single hop, with the role of every AWS service.
Scenario 2: How a static .js file is served (S3 + CloudFront)#
Your Next.js app produces a build output: /_next/static/chunks/main-abc123.js (500 KB). This file never changes — it's a static asset. Serving it from your pod wastes CPU. Instead, push it to S3 and serve via CloudFront.
Scenario 3: What if the server itself serves the .js file (no CDN)?#
In a default Next.js deployment without a CDN, the Next.js pod serves both the HTML page AND the static JS/CSS bundles. Here's what that flow looks like — and why it's slower.
Scenario 4: The full picture — HTML + API + Static JS + Search + Logs#
Now let's combine everything into the real production flow. A user visits www.xyz.com, the page loads, fetches data from the API, searches for products, and every service plays its part.
19. Complete AWS Deployment — Next.js + Java on EKS#
Step-by-step deployment#
Step 1: Write Dockerfiles#
Multi-stage builds reduce image size and attack surface.
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Stage 2: Production (only built output + node_modules)
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./
EXPOSE 3000
CMD ["npm", "start"]
# Stage 1: Build
FROM maven:3.9-eclipse-temurin-21 AS builder
WORKDIR /app
COPY pom.xml .
RUN mvn dependency:go-offline # Cache dependencies
COPY src ./src
RUN mvn package -DskipTests
# Stage 2: Slim JRE runtime
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=builder /app/target/api-*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
Step 2: Push images to Amazon ECR#
# Create repositories
aws ecr create-repository --repository-name nextjs-app
aws ecr create-repository --repository-name java-api
# Authenticate Docker with ECR
aws ecr get-login-password --region ap-south-1 | \
docker login --username AWS --password-stdin 123456789.dkr.ecr.ap-south-1.amazonaws.com
# Tag and push
docker tag nextjs-app:latest 123456789.dkr.ecr.ap-south-1.amazonaws.com/nextjs-app:v2.1.0
docker push 123456789.dkr.ecr.ap-south-1.amazonaws.com/nextjs-app:v2.1.0
docker tag java-api:latest 123456789.dkr.ecr.ap-south-1.amazonaws.com/java-api:v1.4.0
docker push 123456789.dkr.ecr.ap-south-1.amazonaws.com/java-api:v1.4.0
Step 3: Create the EKS Cluster#
apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig
metadata:
name: my-production-cluster
region: ap-south-1
version: "1.30"
managedNodeGroups:
- name: workers
instanceType: t3.xlarge # 4 vCPU, 16 GB
desiredCapacity: 3
minSize: 2
maxSize: 10 # Cluster Autoscaler can scale to 10
availabilityZones: # Spread across AZs for HA
- ap-south-1a
- ap-south-1b
- ap-south-1c
privateNetworking: true # Nodes in private subnets
iam:
withAddonPolicies:
ebs: true # EBS CSI driver
albIngress: true # AWS LB Controller
cloudWatch: true # Logging
eksctl create cluster -f eksctl-cluster.yaml
# Takes ~15 minutes. Creates: VPC, subnets, NAT gateways, EKS control plane, node group.
Step 4: Install essential add-ons#
# 1. AWS Load Balancer Controller (for Ingress → ALB)
helm repo add eks https://aws.github.io/eks-charts
helm install aws-load-balancer-controller eks/aws-load-balancer-controller \
-n kube-system --set clusterName=my-production-cluster
# 2. EBS CSI Driver (for persistent volumes)
eksctl create addon --name aws-ebs-csi-driver --cluster my-production-cluster
# 3. Metrics Server (required for HPA)
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
# 4. Cluster Autoscaler or Karpenter (node autoscaling)
helm install karpenter oci://public.ecr.aws/karpenter/karpenter --namespace karpenter --create-namespace
Step 5: Create namespace, secrets, and configmaps#
kubectl create namespace production
kubectl create secret generic db-credentials -n production \
--from-literal=host=mydb.abc123.ap-south-1.rds.amazonaws.com \
--from-literal=username=admin \
--from-literal=password='S3cureP@ss!'
kubectl create configmap app-config -n production \
--from-literal=REDIS_HOST=my-redis.abc123.cache.amazonaws.com \
--from-literal=S3_BUCKET=my-app-uploads \
--from-literal=LOG_LEVEL=info
Step 6: Apply Deployments#
Apply the java-api Deployment YAML (shown in section 9) and a similar one for Next.js. Both reference ECR images and inject secrets/configmaps as environment variables.
kubectl apply -f java-api-deployment.yaml -n production
kubectl apply -f nextjs-deployment.yaml -n production
# Verify
kubectl get pods -n production -o wide
# NAME READY STATUS NODE AGE
# java-api-abc123-d4e5f 1/1 Running ip-10-0-1-45 30s
# java-api-abc123-g6h7i 1/1 Running ip-10-0-2-78 28s
# nextjs-xyz789-j8k9l 1/1 Running ip-10-0-1-45 30s
# nextjs-xyz789-m0n1o 1/1 Running ip-10-0-3-12 29s
Step 7: Create Services#
kubectl apply -n production -f - <<EOF
apiVersion: v1
kind: Service
metadata:
name: java-api-svc
spec:
selector:
app: java-api
ports:
- port: 8080
targetPort: 8080
type: ClusterIP
---
apiVersion: v1
kind: Service
metadata:
name: nextjs-svc
spec:
selector:
app: nextjs
ports:
- port: 3000
targetPort: 3000
type: ClusterIP
EOF
Step 8: Create the Ingress#
kubectl apply -n production -f - <<EOF
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: app-ingress
annotations:
kubernetes.io/ingress.class: alb
alb.ingress.kubernetes.io/scheme: internet-facing
alb.ingress.kubernetes.io/target-type: ip
alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:ap-south-1:123456789:certificate/abc-123
alb.ingress.kubernetes.io/listen-ports: '[{"HTTPS":443}]'
alb.ingress.kubernetes.io/ssl-redirect: "443"
spec:
rules:
- host: app.example.com
http:
paths:
- path: /api
pathType: Prefix
backend:
service:
name: java-api-svc
port:
number: 8080
- path: /
pathType: Prefix
backend:
service:
name: nextjs-svc
port:
number: 3000
EOF
# Get the ALB DNS name
kubectl get ingress -n production
# → app-ingress app.example.com k8s-prod-abc123-456.ap-south-1.elb.amazonaws.com
Step 9: Configure DNS#
In Route 53, create an A record alias for app.example.com pointing to the ALB. Users hit your domain → Route 53 → ALB → Ingress → Service → Pod.
Step 10: Set up autoscaling#
# HPA for Next.js: scale 2-8 pods when CPU > 60%
kubectl autoscale deployment nextjs -n production --min=2 --max=8 --cpu-percent=60
# HPA for Java: scale 2-6 pods when CPU > 70%
kubectl autoscale deployment java-api -n production --min=2 --max=6 --cpu-percent=70
# Karpenter handles node scaling automatically
Step 11: Monitoring and observability#
Install Prometheus (metrics collection), Grafana (dashboards), and set up CloudWatch Container Insights. Configure alerts for: pod restarts > 3/hour, CPU > 85% sustained, 5xx error rate > 1%, pod pending > 2 minutes.
20. Complete Request Lifecycle#
This is the single most important diagram in the entire guide. It traces every network hop, every K8s component, and every AWS service touched when a real user visits your app.
The two paths summarised#
| Step | / (page load) | /api/* (API call) |
|---|---|---|
| ① DNS | Route 53 resolves app.example.com → ALB CNAME → ALB IPs | Route 53 resolves app.example.com → ALB CNAME → ALB IPs |
| ② ALB | TLS terminates (ACM cert). WAF scans for attacks. Reads HTTP path. | TLS terminates (ACM cert). WAF scans for attacks. Reads HTTP path. |
| ③ Ingress | path: / → nextjs-svc (ClusterIP) | path: /api → java-api-svc (ClusterIP) |
| ④ Pod | Next.js runs SSR — calls java-api-svc internally for data | Java processes business logic directly |
| ⑤ Data | N/A (Next.js delegates to Java) | Redis cache check → RDS query → S3 if file needed |
| ⑥ Response | HTML with <script> tags for JS bundles | JSON response |
| ⑦ Static assets | Browser fetches .js/.css → CloudFront edge (5ms) → S3 origin if miss | N/A |
| ⑧ Return | Response travels: Pod → ALB (re-encrypts TLS) → Browser | Response travels: Pod → ALB (re-encrypts TLS) → Browser |
21. Debugging Cheat Sheet#
# ─── CLUSTER STATUS ─────────────────────────────
kubectl cluster-info # API server endpoint
kubectl get nodes -o wide # Node IPs, OS, K8s version
kubectl top nodes # CPU/memory per node
kubectl get events --sort-by=.lastTimestamp # Recent cluster events
# ─── POD DEBUGGING ──────────────────────────────
kubectl get pods -n production -o wide # Pod status, IP, node
kubectl describe pod java-api-xyz -n production # Full details + events
kubectl logs java-api-xyz -n production -f # Stream live logs
kubectl logs java-api-xyz --previous # Logs from crashed container
kubectl exec -it java-api-xyz -n production -- /bin/sh # Shell into pod
kubectl port-forward java-api-xyz 8080:8080 # Access pod locally
# ─── DEPLOYMENT OPERATIONS ──────────────────────
kubectl rollout status deploy/java-api -n production # Watch rollout
kubectl rollout history deploy/java-api -n production # See revisions
kubectl rollout undo deploy/java-api -n production # Instant rollback
kubectl rollout undo deploy/java-api --to-revision=3 # Rollback to specific version
# ─── SERVICE / NETWORKING ───────────────────────
kubectl get svc -n production # List services + ClusterIPs
kubectl get endpoints java-api-svc # Which pods are backing the service?
kubectl get ingress -n production # Ingress rules + ALB DNS
kubectl run debug --rm -it --image=busybox -- nslookup java-api-svc.production.svc.cluster.local
# ─── SCALING ────────────────────────────────────
kubectl scale deploy/java-api --replicas=5 -n production # Manual scale
kubectl get hpa -n production # HPA status + current metrics
kubectl top pods -n production # CPU/memory per pod
# ─── DANGER ZONE ────────────────────────────────
kubectl delete pod java-api-xyz -n production # Kill a pod (Deployment recreates it)
kubectl drain node-01 --ignore-daemonsets # Evacuate a node for maintenance
kubectl cordon node-01 # Mark node as unschedulable
22. Complete Glossary#
- Cluster: The entire Kubernetes system — control plane + worker nodes together. Everything runs inside one cluster.
- Pod: Smallest schedulable unit. Wraps 1+ containers with shared network/storage. Gets its own IP. Ephemeral — never rely on a specific pod staying alive.
- Node: A machine (physical or VM) that runs pods. Has kubelet, kube-proxy, and container runtime.
- Deployment: Manages ReplicaSets which manage Pods. Handles rolling updates and rollbacks. The primary way to run stateless apps.
- StatefulSet: Like Deployment but for stateful apps (databases). Pods get stable network identities (pod-0, pod-1) and persistent storage. Ordered, graceful deployment and scaling.
- DaemonSet: Ensures one pod runs on every node (or a subset). Used for log collectors, monitoring agents, node-level tools.
- Job / CronJob: Job runs a pod to completion (batch processing). CronJob runs Jobs on a schedule (nightly backups, reports).
- Service: Stable network endpoint for a set of pods. ClusterIP (internal), NodePort (external via node), LoadBalancer (cloud LB), ExternalName (DNS alias).
- Ingress: HTTP routing rules. Maps hostnames and paths to Services. Needs an Ingress Controller to work.
- ConfigMap: Stores non-sensitive configuration as key-value pairs. Injected into pods as env vars or mounted files.
- Secret: Stores sensitive data (base64 encoded). Same injection mechanisms as ConfigMap. Enable encryption at rest in production.
- Namespace: Virtual cluster inside a physical cluster. Provides resource isolation, RBAC boundaries, and resource quotas.
- Label: Key-value pairs attached to objects (pods, nodes). Used by selectors to group and filter objects. Example:
app=java-api, env=production. - Annotation: Key-value metadata on objects that's NOT used for selection. For tooling: build info, last-applied config, Prometheus scraping config.
- Helm: Package manager for Kubernetes. Helm Charts bundle K8s YAML files into reusable, versioned, configurable packages. Like apt or npm for clusters.
- IRSA: IAM Roles for Service Accounts. Assigns AWS IAM roles to K8s ServiceAccounts so pods can access AWS services (S3, RDS) without hardcoded credentials.
- CRI: Container Runtime Interface. The standard API that kubelet uses to talk to any container runtime (containerd, CRI-O). Docker was removed as a direct runtime in K8s 1.24.
- CNI: Container Network Interface. Plugin that implements pod networking. AWS VPC CNI gives pods real VPC IPs. Calico and Cilium are alternatives with NetworkPolicy support.
- CSI: Container Storage Interface. Plugin API for storage providers. AWS EBS CSI Driver handles EBS volumes, EFS CSI for NFS, etc.