All writing

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.
kubernetes
devops
aws

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:

Without Kubernetes — Manual Container Management Server 1 — OVERLOADED App ×3 DB Redis CPU 98% · Memory 95% Server 2 — IDLE App ×1 CPU 12% · Memory 20% Server 3 — DEAD App ✗ crashed No one knows it's down until users complain Problems you must solve manually: ❌ Which server should a new container run on? (you SSH in and decide) ❌ Container crashed at 3 AM? Nobody restarts it until morning. ❌ Traffic spike? You manually docker run more copies and manually set up a load balancer. ❌ Deploying a new version? Stop old containers → users get errors → start new containers.

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.

$ kubectl / CI Pipeline / Dashboard HTTPS (REST) CONTROL PLANE (Master Nodes) kube-apiserver REST gateway · AuthN · AuthZ · Admission The ONLY component that writes to etcd etcd Distributed key-value store Raft consensus · 3 or 5 nodes read/write kube-scheduler Watches unscheduled pods Filter → Score → Bind to node kube-controller-manager ReplicaSet controller Node controller · Job controller ServiceAccount controller · Endpoints ctrl cloud-controller-manager Node ctrl (registers EC2 instances) Route ctrl (VPC networking) Service ctrl (provisions AWS ALB/NLB) CoreDNS Cluster DNS server svc-name.namespace.svc.cluster.local WORKER NODES (Data Plane) Worker Node 1 (EC2 i-0abc123) t3.xlarge · 4 vCPU · 16 GB · AZ: ap-south-1a kubelet kube-proxy containerd POD: nextjs-abc12 nextjs:v2.1.0 :3000 IP: 10.244.1.5 · CPU: 250m/500m POD: java-api-xyz98 java-api:v1.4.0 :8080 IP: 10.244.1.9 · CPU: 500m/1000m Ubuntu 22.04 · Linux kernel 5.15 · cgroup v2 EBS gp3 root volume · EBS CSI driver installed Worker Node 2 (EC2 i-0def456) t3.xlarge · 4 vCPU · 16 GB · AZ: ap-south-1b kubelet kube-proxy containerd POD: nextjs-def34 nextjs:v2.1.0 :3000 IP: 10.244.2.3 · replica #2 POD: java-api-mno56 java-api:v1.4.0 :8080 IP: 10.244.2.7 · replica #2 Ubuntu 22.04 · Linux kernel 5.15 · cgroup v2 kubelet reports status kubelet reports status
Full cluster architecture — every component and how they communicate

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 Anatomy — Single Container vs Multi-Container Single-Container Pod (99% of cases) IP: 10.244.1.5 · Status: Running Container: java-api image: java-api:v1.4.0 · port: 8080 Pause container (hidden, holds network ns) pause:3.9 — keeps pod alive even if main container restarts Multi-Container Pod (sidecar pattern) IP: 10.244.2.9 · all containers share this IP Main: java-api :8080 your application Sidecar: envoy-proxy :15001 Istio service mesh proxy — handles mTLS, retries Sidecar: fluentbit ships logs from /var/log to CloudWatch Shared Volume /var/log (emptyDir) Shared Network localhost:8080 ↔ :15001

Pod Lifecycle States#

Pending Running Succeeded Failed Unknown Pending: Waiting for scheduling or image pull Succeeded: All containers exited 0 (Jobs) Unknown: Node lost contact

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.

Worker Node — Internal Structure kubelet • Registers node with API Server • Watches for assigned pods • Tells containerd to pull & run • Runs liveness/readiness probes • Reports node status every 10s • Manages pod volumes & secrets kube-proxy • Maintains network rules (iptables or IPVS) on the node • Implements Service abstraction • Round-robin load balancing • Handles ClusterIP, NodePort, LoadBalancer traffic routing containerd • Container runtime (CRI) • Pulls images from registries • Creates/starts/stops containers • Manages container filesystem • Replaced Docker as of K8s 1.24 • Uses runc under the hood Node Conditions (kubelet reports these) Ready=TrueNode is healthy and accepting pods Ready=FalseNode is unhealthy. kubelet stopped or node has issues. Ready=UnknownNo heartbeat for 40s. Node might be dead. MemoryPressureMemory is low → kubelet starts evicting pods DiskPressureDisk space is low → kubelet stops accepting new pods

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#

How Control Plane Components Interact API Server AuthN → AuthZ → Admission → etcd Every component talks ONLY through this etcd cluster 3 nodes · Raft consensus All cluster state lives here Scheduler Watches unscheduled pods Assigns them to best node WATCH + POST Controller Manager • ReplicaSet controller • Deployment controller • Node controller • Job / CronJob controller Cloud Controller • Provisions load balancers • Manages cloud routes • Attaches EBS volumes • Sets node addresses kubelets on every worker node WATCH pods assigned to their node, report status back
All arrows go through the API Server — no component talks to any other directly

What happens inside the API Server (request pipeline)#

Authentication Who are you? Authorization RBAC: Can you do this? Admission Control Mutate/Validate request Validation Schema check Persist to etcd Write confirmed
  • 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.

Master Node vs Worker Node — Side by Side Master Node (Control Plane Node) Does NOT run your application pods (by default) kube-apiserver kube-scheduler kube-controller-manager cloud-controller-manager etcd (cluster database) kubelet kube-proxy Worker Node (Data Plane Node) Runs YOUR application pods kubelet kube-proxy containerd (container runtime) Pod: nextjs your frontend Pod: java-api your backend Pod: redis Pod: fluentbit
Master nodes run the brain; Worker nodes run your apps. Both have kubelet and kube-proxy.

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#

Scheduler Decision Process New Pod nodeName: (empty) needs: 500m CPU, 1Gi RAM FILTER (predicates) ✗ Node A: only 200m CPU free ✗ Node B: tainted NoSchedule ✗ Node C: wrong AZ (affinity) ✓ Node D: 2000m CPU, 4Gi free ✓ Node E: 1500m CPU, 3Gi free ✓ Node F: 800m CPU, 2Gi free SCORE (priorities) LeastRequestedPriority: Node D: 80 (most headroom) Node E: 65 Node F: 40 InterPodAffinity: Node E: +20 (preferred zone) Winner: Node E (85 total) BIND API Server updates pod.spec.nodeName = "Node E" Built-in scoring functions LeastRequestedPriority — prefer nodes with more free resources BalancedResourceAllocation — prefer nodes where CPU and memory usage are similar SelectorSpreadPriority — spread pods across zones and nodes to improve availability

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.

How a Service routes traffic (kube-proxy iptables mode) Next.js Pod calls java-api-svc:8080 DNS lookup CoreDNS → returns 10.96.0.14 Service: java-api-svc ClusterIP: 10.96.0.14:8080 kube-proxy (iptables rules) random iptables probability rules (⅓ each) Pod: java-api-a1b2c 10.244.1.5:8080 Ready ✓ Pod: java-api-d3e4f 10.244.2.9:8080 Ready ✓ Pod: java-api-g5h6i 10.244.3.2:8080 Ready ✓

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#

Deployment manages ReplicaSet manages Pod replica 1 Pod replica 2 Pod replica 3 You NEVER create ReplicaSets directly. Deployments manage them.

Rolling Update — visualized#

Rolling update: v1 → v2 (maxUnavailable:1, maxSurge:1) t=0 v1 v1 v1 3 v1 pods running t=1 v1 v1 v1 ↓ v2 ↑ Kill 1 old, create 1 new (surge) t=2 v1 v1 ↓ v2 ✓ v2 ↑ v2 pod ready, kill next v1 t=3 v2 ✓ v2 ✓ v2 ✓ ✓ Complete! Zero downtime. At every step, at least 2 pods are serving traffic. Users never see an error. If v2 fails readinessProbe, the rollout pauses automatically. Run kubectl rollout undo to revert.

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 failureThreshold times 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#

Relationship: deployment.yaml creates pods, service.yaml exposes them pod.yaml Creates a SINGLE pod • No auto-restart if it dies • No scaling (always exactly 1) • No rolling updates • No rollbacks ❌ Almost NEVER used in prod Use only for: one-off debugging, quick tests, learning K8s deployment.yaml Creates MULTIPLE managed pods • Auto-restarts crashed pods • Scale to N replicas • Rolling updates built-in • Rollback to any revision ✅ THE standard way to run apps Contains a pod template inside it — so pod.yaml is redundant service.yaml Creates a NETWORK endpoint • Stable IP + DNS name • Load-balances across pods • Survives pod restarts • Required for pod-to-pod comms ✅ Needed if anything talks TO your pods (other pods, users, load balancers) deployment.yaml already contains the pod template: pod spec is embedded inside deployment deployment.yaml contains spec.template (= the pod spec): spec.template.spec.containers → exactly the same fields as a standalone pod.yaml spec.template.metadata.labels → must match spec.selector.matchLabels AND service selector So deployment.yaml = pod.yaml + replication + rolling updates + rollback. That's why pod.yaml is never used directly.

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?#

Minimum → Typical → Full Production Stack Minimum (it runs) ✓ deployment.yaml That's it. Pods run. But nothing can talk to them from outside or from other pods (no Service). Useful for: batch jobs, workers that only consume from a queue. Typical (functional) ✓ deployment.yaml ✓ service.yaml Now pods have a stable endpoint. Other pods can call this service. Add Ingress if external users need to reach it. Production (complete) ✓ deployment.yaml ✓ service.yaml ✓ ingress.yaml ✓ configmap.yaml ✓ secret.yaml (or external) ✓ hpa.yaml (autoscaling) ✓ networkpolicy.yaml

10. High Availability — When the Control Plane Fails#

HA Control Plane — 3 masters across Availability Zones Master 1 (AZ-a) ✓ LEADER API Server (active) Scheduler (active — won leader election) Controller Mgr (active — won election) etcd member 1 (LEADER) All writes go through this etcd leader Master 2 (AZ-b) standby API Server (active — all API servers are active) Scheduler (standby — lost leader election) Controller Mgr (standby) etcd member 2 (follower) Master 3 (AZ-c) standby API Server (active) Scheduler (standby) Controller Mgr (standby) etcd member 3 (follower) Internal NLB — balances API traffic across all 3 If Master 1 dies: etcd: member 2 or 3 elected new leader (Raft). Scheduler/Controller Mgr: new leader election in ~15s. API traffic: NLB routes to 2 & 3. No downtime.

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.

Ingress: Host-based + Path-based Routing Internet → DNS → AWS ALB AWS ALB (TLS terminates here) AWS Load Balancer Controller (Ingress Controller) app.example.com/ → nextjs-svc:3000 app.example.com/api/* → java-api-svc:8080 admin.example.com/* → admin-svc:3001 (host-based) next #1 next #2 java #1 java #2 admin #1 TLS:ACM certificate on the ALB handles HTTPS. Traffic inside the cluster is plain HTTP (encrypted by the mesh if using Istio). Default backend:Requests matching no rule → 404 page or a custom fallback service.

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. /api matches /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. /api matches only /api and 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.name share 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.

Tracing www.xyz.com — Every IP in the Chain Step 1: DNS Resolution www.xyz.com → Route 53 (or your DNS) → returns ALB IP addresses (e.g. 52.66.148.23, 13.234.76.112) Step 2: Load Balancer (the public IP you see) These IPs belong to the AWS ALB — NOT to Ingress, NOT to pods. ALB has multiple IPs (one per AZ). This is the Ingress entry point. Step 3: Ingress Controller reads the rules ALB routes to the Ingress Controller pod. The controller matches the Host header and path to an Ingress rule → picks the right Service. Step 4: Service (virtual IP — ClusterIP) Service IP (e.g. 10.96.0.14) is internal only — not reachable from the internet. kube-proxy's iptables rules translate it to a real pod IP. Step 5: Pod (the actual container running your code) Pod IP (e.g. 10.244.1.5) — this is a VPC-internal IP. With target-type: ip, the ALB routes directly here, skipping the Service VIP. IP chain summary: Public ALB IP (52.66.x.x) → [Ingress Controller Pod IP] → Service ClusterIP (10.96.x.x) → Pod IP (10.244.x.x)

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"?#

All the IPs involved, from outside to inside ALB Public IP 52.66.148.23 Ingress Ctrl Pod 10.244.0.3 Service ClusterIP 10.96.0.14 Pod IP 10.244.1.5 Container localhost:8080 Public (internet) Cluster-internal Virtual (iptables) Real VPC IP Inside the pod With target-type: ip (AWS ALB), the ALB skips the Service VIP and sends directly to Pod IP: ALB (52.66.x.x) → Pod IP (10.244.1.5:8080) — faster, fewer hops

13. Persistent Storage#

Storage Architecture: PVC → PV → Physical Disk Pod (java-api) mountPath: /data mounts PersistentVolumeClaim "I need 20Gi, ReadWriteOnce" binds to PersistentVolume 20Gi gp3 · Bound provisioned by StorageClass ebs.csi.aws.com · gp3 AWS EBS Real SSD disk in AZ Dynamic provisioning: you create the PVC, the StorageClass automatically creates the PV and the EBS volume.
  • 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#

Three Levels of Autoscaling HPA Horizontal Pod Autoscaler Scales the number of pod replicas based on CPU, memory, or custom metrics (requests/sec, queue depth). Example: CPU > 70% → add pods Example: CPU < 30% → remove pods VPA Vertical Pod Autoscaler Adjusts resource requests/limits for individual pods. If a pod consistently uses only 100m of a 500m request, VPA lowers the request. Restarts the pod to apply. Cluster Autoscaler (or Karpenter on AWS) Scales the number of NODES. If pods can't be scheduled (not enough capacity), it adds new EC2 instances. If nodes are underutilized for 10+ min, it removes them.

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=nextjs can reach pods with label app=java-api on port 8080."

18. The Reconciliation Loop — How K8s Self-Heals#

Every controller runs this loop continuously 1. OBSERVE Watch actual state via API Server "Currently 2 pods running" 2. DIFF Compare with desired state "Desired 3, actual 2 → drift!" 3. ACT Create/delete resources to converge "Create 1 new pod" Loop repeats every few seconds — endlessly Pod dies → ReplicaSet ctrl sees 2/3 → creates new pod Node dies → Node ctrl marks it NotReady → pods rescheduled → ReplicaSet ctrl fills the gap

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#

AWS Services Map — How They Relate to Each Other User types www.xyz.com in browser Route 53 (DNS) "Phone book of the internet" — translates names → IPs CloudFront (CDN) Caches static files at 400+ global edge locations or ALB (Load Balancer) Distributes traffic across multiple targets K8s workloads or direct EC2 EKS (Kubernetes) Managed K8s — AWS runs the control plane You define Deployments, K8s places pods on EC2 ← your Next.js + Java pods run here EC2 (Virtual Machines) Bare servers you rent by the hour EKS worker nodes ARE EC2 instances t3.xlarge = 4 vCPU, 16 GB RAM EKS pods run ON EC2 instances Backend Data Services RDS Managed database PostgreSQL / MySQL Auto-backups, replicas ElastiCache Managed Redis / Memcached In-memory caching Sub-ms latency S3 (Storage Bucket) Infinite file storage Static files, images, backups $0.023/GB/month OpenSearch (ES) Full-text search engine Logs, analytics, search bar Kibana dashboards Supporting Services ECR Docker image registry Like Docker Hub, but private ACM Free TLS/SSL certificates Auto-renews, attach to ALB IAM Permissions & access control Who can do what to which resource CloudWatch Logs, metrics, alarms Like Datadog but AWS-native VPC Your private network in AWS Subnets, route tables, NAT WAF Web firewall on ALB Blocks SQL injection, bots, DDoS SQS / SNS Message queues & pub/sub Async jobs, event-driven Secrets Manager Encrypted secrets vault Auto-rotates DB passwords K8s (Kubernetes) Not an AWS service — it's the open-source orchestrator that runs ON AWS (via EKS). K8s is the "brain" that tells EC2 instances which containers to run. "K8s" = K + 8 letters (ubernete) + s. Pronounced "kates" or "kubernetes." Created by Google, now maintained by the CNCF.
Every AWS service and how they connect — from user request to data storage

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 like 52.66.148.23. That table has rows like: www.xyz.com → A → 52.66.148.23 (A record = an IPv4 address) or www.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. K8s is 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-1c are 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.

GET https://api.xyz.com/greet — full request flow ① DNS Lookup Browser → "What IP is api.xyz.com?" → Route 53 looks up DNS table → finds CNAME → k8s-prod.elb.amazonaws.com → resolves to 52.66.148.23 ② TLS + Load Balancer Browser opens HTTPS to 52.66.148.23 → AWS ALB terminates TLS (using ACM certificate) → ALB reads path: /greet → matches Ingress target group ③ Into the EKS Cluster ALB (target-type: ip) sends to Pod IP 10.244.1.5:8080 directly on EC2 worker node. kube-proxy iptables resolve Service if target-type is instance. ④ Pod handles the request Container receives GET /greet on port 8080 → your Java code runs → returns {"message": "Hello!"} → response travels back: Pod → ALB → Browser Role of each service in this request Route 53 Translated domain name → ALB address DNS table lookup ALB + ACM TLS termination Path-based routing Public entry point EKS + K8s Scheduled the pod Keeps it alive & healthy Orchestration EC2 Physical machine where the pod's container runs Compute Services NOT involved in this specific request: S3 — no static files needed. CloudFront — not serving cached content. ES/OpenSearch — no search query. RDS/ElastiCache — the /greet endpoint doesn't query a database (but /api/users would hit RDS via the pod). Time breakdown for this request DNS: ~5ms TLS: ~15ms ALB route: ~3ms K8s routing: ~2ms App process: ~25ms Total: ~50ms First request is slower (DNS + TLS handshake). Subsequent requests reuse the TLS connection: ~30ms.
GET /greet — every service's role from browser to response

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.

Static JS file: Browser → CloudFront → S3 (CDN path) Browser GET /main-abc123.js Route 53 cdn.xyz.com → CF CloudFront Edge Mumbai edge (closest to user) Cache HIT? → return file instantly Cache HIT → 5ms response 🚀 MISS S3 Bucket Origin: the actual file How this works: 1. You run npm run build → produces .next/static/ folder with JS, CSS, and image files 2. CI/CD pipeline uploads these files to S3 bucket: aws s3 sync .next/static/ s3://my-app-static/ 3. CloudFront distribution has S3 as its "origin" — when a file is requested, CF checks its edge cache first 4. First request (cache MISS): CF fetches from S3 (100ms) → caches it → returns to user. TTL: 24 hours. 5. Every subsequent request (cache HIT): CF returns from Mumbai edge → 5ms. S3 is never touched again until TTL expires. Route 53 setup: cdn.xyz.com → CNAME → d111abc.cloudfront.net (CloudFront distribution domain)
Static assets go through CDN — blazing fast, no load on your server pods

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.

Without CDN: Server pod serves both HTML and static JS Request 1: GET / (the HTML page) Browser Route 53 ALB K8s Service Next.js Pod (SSR) Pod runs React SSR → returns HTML HTML includes: <script src="/main.js"> Request 2: GET /_next/static/chunks/main-abc123.js (triggered by the HTML) Browser same TLS connection (HTTP/2) ALB K8s Service Next.js Pod (static) Pod reads .js from its filesystem and returns it — wastes CPU Comparison: Server-served vs CDN-served static files ❌ Without CDN (pod serves .js) • Every .js request hits your pod → wastes CPU • Latency: 50-200ms (server in one region) • Pod scales up under static file load • Bandwidth: paid at EC2 egress rate • User in Tokyo: 200ms+ round trip to Mumbai • Traffic spike = pods overwhelmed by .js requests Fine for dev/small apps. Not scalable. ✅ With CDN (CloudFront + S3) • .js served from edge → pod never touched • Latency: 5-20ms (cached at nearest edge) • Pod handles only dynamic requests (/api) • Bandwidth: CF pricing (much cheaper) • User in Tokyo: 5ms from Tokyo edge • Traffic spike = CF handles it (infinite scale) Production standard. Always use this.
Server-served static files waste pod CPU — CDN offloads them to the edge

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.

Complete Production Flow — Every AWS Service in Action User visits www.xyz.com ① Route 53 (DNS lookup) static assets HTML + API ② CloudFront Edge (CDN) Serves .js, .css, images — 5ms S3 (origin, cache miss only) ③ ALB (Load Balancer + TLS) WAF checks → TLS terminates → path routing path: / path: /api EKS Cluster (on EC2 instances) ④ Next.js Pod (SSR) Renders HTML, calls java-api internally ⑤ Java API Pod Business logic, data access ClusterIP DNS ⑧ Fluentbit (sidecar) Ships logs from all pods ⑥ RDS (PostgreSQL) Users, orders, products ⑥ ElastiCache (Redis) Session cache, API cache ⑧ CloudWatch Logs, metrics, alarms ⑦ OpenSearch Product search Full request sequence when user loads the product search page: ① DNS→ resolves domain ② CloudFront→ serves JS/CSS from edge ③ ALB→ routes to K8s ④ Next.js→ SSR HTML ⑤ Java API→ handles /api/search ⑥ RDS+Redis→ data layer ⑦ OpenSearch→ full-text search query ("wireless headphones") ⑧ CloudWatch→ every log, metric, and error is shipped here
Every AWS service in one flow — from DNS to CDN to K8s pods to databases to logs

19. Complete AWS Deployment — Next.js + Java on EKS#

Production Architecture on AWS Users (browsers, mobile apps) Route 53 (DNS) AWS WAF AWS ALB + ACM TLS Certificate Amazon EKS Cluster (managed control plane + worker nodes) AWS LB Controller (Ingress) Service: nextjs-svc (ClusterIP:3000) — path: / HPA: 2-8 replicas · CPU target: 60% next:v2 #1 next:v2 #2 next:v2 #3 Service: java-api-svc (ClusterIP:8080) — path: /api HPA: 2-6 replicas · CPU target: 70% java:v1 #1 java:v1 #2 java:v1 #3 Node Group: t3.xlarge × 3 (ap-south-1a,b,c) Karpenter auto-scales nodes on demand Managed AWS Services (outside the cluster) RDS (PostgreSQL) ElastiCache (Redis) S3 (files) ECR (images) CloudWatch (logs/metrics) Pods access RDS/Redis via VPC private subnets — no public internet needed. IAM Roles for Service Accounts (IRSA) for S3/ECR access.

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.

What happens when a user visits app.example.com 👤 User's Browser types app.example.com ① Route 53 (DNS) CNAME → ALB IPs: 52.66.x.x ② AWS ALB + WAF + ACM TLS terminates · WAF scans · reads HTTP path path: / path: /api/* ③a Ingress → nextjs-svc kube-proxy resolves ClusterIP → Pod IP ④a Next.js Pod (SSR) Renders HTML on server side IP: 10.244.1.12 on EC2 node-1 internal call: java-api-svc:8080 (ClusterIP DNS, never leaves cluster) ③b Ingress → java-api-svc ALB target group → round-robin ④b Java API Pod Processes business logic IP: 10.244.2.9 on EC2 node-2 ⑤ RDS PostgreSQL SELECT * FROM users ⑤ ElastiCache Redis: check cache first ⑤ S3 file uploads ⑥ Next.js returns HTML includes <script src="/main.js"> ⑦ CloudFront Edge (CDN) Browser fetches .js/.css → served from cache (5ms) S3 Bucket (origin, if cache miss) ⑧ Response: Pod → ALB (re-encrypts TLS) → Browser API: JSON · Page: HTML · Assets: from CDN cache. Total: ~50-200ms first load. CloudWatch Logs all pod logs →
Complete request lifecycle — both paths with CDN, data layer, and logging shown

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.