# Kubernetes: The Complete Guide (With Code & Docker)

## 🌱 **Chapter 1: What is Kubernetes? Why Should You Care?**

> 🧩 **Analogy**:  
> Imagine you’re managing a **fleet of delivery drones**.
> 
> * You don’t manually fly each one.
>     
> * You define: *how many drones*, *what packages they carry*, *where to deliver*, *what to do if one crashes*.
>     
> * A **central system** (Kubernetes) handles scheduling, healing, scaling, and routing.
>     
> 
> That’s Kubernetes.

### ✅ What is Kubernetes?

* **Open-source container orchestration system** (originally by Google, now CNCF).
    
* Automates **deployment, scaling, and management** of containerized apps.
    
* Works with **Docker, containerd, CRI-O**.
    

### ✅ Why Kubernetes?

| Problem | Kubernetes Solution |
| --- | --- |
| Manual container management | ✅ Auto-deploy, heal, scale |
| App downtime | ✅ Self-healing (restarts failed containers) |
| Scaling manually | ✅ Horizontal Pod Autoscaler |
| Networking complexity | ✅ Built-in Service Discovery & Load Balancing |
| Config/Secret sprawl | ✅ ConfigMap & Secret |
| Multi-cloud | ✅ Runs anywhere: AWS, GCP, Azure, On-Prem |

---

## ⚙️ **Chapter 2: Setup Your Kubernetes Playground**

### ✅ Option 1: Minikube (Beginner Friendly)

```bash
# Install Minikube
brew install minikube  # macOS
# or download from https://minikube.sigs.k8s.io/docs/start/

# Start cluster
minikube start --driver=docker

# Check status
minikube status

# Open dashboard
minikube dashboard
```

### ✅ Option 2: Kind (Kubernetes IN Docker — Production-like)

```bash
# Install Kind
brew install kind

# Create cluster
kind create cluster --name my-cluster

# Switch context
kubectl config use-context kind-my-cluster
```

### ✅ Option 3: Cloud (EKS, GKE, AKS) — Later

---

## 🐳 **Chapter 3: Docker + Kubernetes — The Perfect Pair**

> 🧩 **You MUST containerize your app first.**

### ✅ Step 1: Write a Dockerfile

```dockerfile
# Dockerfile
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY . .

EXPOSE 3000

CMD ["npm", "start"]
```

### ✅ Step 2: Build & Tag

```bash
docker build -t my-react-app:1.0 .
```

### ✅ Step 3: Test Locally

```bash
docker run -p 3000:3000 my-react-app:1.0
```

### ✅ Step 4: Push to Registry (Optional for Minikube/Kind)

```bash
# For Minikube — load image directly
minikube image load my-react-app:1.0

# For Kind — load image
kind load docker-image my-react-app:1.0 --name my-cluster

# For Cloud — push to Docker Hub or ECR/GCR
docker tag my-react-app:1.0 your-dockerhub/my-react-app:1.0
docker push your-dockerhub/my-react-app:1.0
```

---

## 🧱 **Chapter 4: Kubernetes Core Concepts — With Code**

> 📌 **Keywords**: `Pod`, `Deployment`, `Service`, `Namespace`, `Label`, `Selector`

---

### ✅ 4.1 Pod — The Smallest Deployable Unit

> A Pod = 1+ containers sharing network/storage. Usually 1 app container.

```yaml
# pod.yaml
apiVersion: v1
kind: Pod
metadata:
  name: my-app-pod
  labels:
    app: my-app
spec:
  containers:
  - name: my-app-container
    image: my-react-app:1.0
    ports:
    - containerPort: 3000
```

```bash
kubectl apply -f pod.yaml
kubectl get pods
kubectl logs my-app-pod
kubectl delete pod my-app-pod
```

> ⚠️ Pods are ephemeral — don’t manage them directly. Use **Deployments**.

---

### ✅ 4.2 Deployment — Manage Pods at Scale

> Manages ReplicaSets → ensures desired number of Pods are running.

```yaml
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app
        image: my-react-app:1.0
        ports:
        - containerPort: 3000
        resources:
          requests:
            memory: "64Mi"
            cpu: "250m"
          limits:
            memory: "128Mi"
            cpu: "500m"
```

```bash
kubectl apply -f deployment.yaml
kubectl get deployments
kubectl get pods -l app=my-app
kubectl scale deployment my-app-deployment --replicas=5
kubectl rollout status deployment/my-app-deployment
kubectl rollout history deployment/my-app-deployment
kubectl rollout undo deployment/my-app-deployment --to-revision=1
```

---

### ✅ 4.3 Service — Expose Your App

> Pods have dynamic IPs. Services provide stable endpoint.

#### ➤ ClusterIP (Internal)

```yaml
# service-clusterip.yaml
apiVersion: v1
kind: Service
metadata:
  name: my-app-service
spec:
  selector:
    app: my-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 3000
```

```bash
kubectl apply -f service-clusterip.yaml
kubectl get svc
# Access from within cluster: http://my-app-service
```

#### ➤ NodePort (External via Node IP)

```yaml
# service-nodeport.yaml
apiVersion: v1
kind: Service
metadata:
  name: my-app-nodeport
spec:
  type: NodePort
  selector:
    app: my-app
  ports:
    - port: 80
      targetPort: 3000
      nodePort: 30001  # Optional (30000-32767)
```

```bash
kubectl apply -f service-nodeport.yaml
minikube ip  # Get node IP
curl $(minikube ip):30001
```

#### ➤ LoadBalancer (Cloud Only)

```yaml
# service-lb.yaml
apiVersion: v1
kind: Service
metadata:
  name: my-app-lb
spec:
  type: LoadBalancer
  selector:
    app: my-app
  ports:
    - port: 80
      targetPort: 3000
```

```bash
kubectl apply -f service-lb.yaml
kubectl get svc  # Wait for EXTERNAL-IP
```

---

## 🗃️ **Chapter 5: Config, Secrets & Storage**

> 📌 **Keywords**: `ConfigMap`, `Secret`, `PersistentVolume`, `PersistentVolumeClaim`, `StorageClass`

---

### ✅ 5.1 ConfigMap — Inject Configuration

```yaml
# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  APP_NAME: "My Awesome App"
  LOG_LEVEL: "info"
```

```yaml
# deployment-with-config.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app-with-config
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app
        image: my-react-app:1.0
        envFrom:
        - configMapRef:
            name: app-config
        ports:
        - containerPort: 3000
```

```bash
kubectl apply -f configmap.yaml
kubectl apply -f deployment-with-config.yaml
kubectl exec <pod-name> -- env | grep APP_NAME
```

---

### ✅ 5.2 Secret — Inject Sensitive Data

```bash
# Create from literal
kubectl create secret generic db-secret \
  --from-literal=DB_HOST=localhost \
  --from-literal=DB_PASS=supersecret

# Or from file
echo -n 'my-password' > ./password.txt
kubectl create secret generic app-secret --from-file=password=./password.txt
```

```yaml
# deployment-with-secret.yaml
envFrom:
- secretRef:
    name: db-secret
```

> 🔐 Secrets are **base64-encoded** (not encrypted). Use **Vault, SealedSecrets, or External Secrets** in prod.

---

### ✅ 5.3 Persistent Storage — Stateful Apps (DBs, File Uploads)

```yaml
# persistentvolumeclaim.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
  storageClassName: standard  # Depends on cluster
```

```yaml
# deployment-with-pvc.yaml
volumeMounts:
- name: data-storage
  mountPath: /app/data

volumes:
- name: data-storage
  persistentVolumeClaim:
    claimName: my-pvc
```

```bash
kubectl apply -f persistentvolumeclaim.yaml
kubectl apply -f deployment-with-pvc.yaml
kubectl exec <pod> -- df -h /app/data
```

---

## 🌐 **Chapter 6: Ingress, Networking & DNS**

> 📌 **Keywords**: `Ingress`, `Ingress Controller`, `NGINX Ingress`, `Host`, `Path`, `TLS`

---

### ✅ 6.1 Install Ingress Controller (Minikube)

```bash
minikube addons enable ingress
kubectl get pods -n ingress-nginx
```

---

### ✅ 6.2 Create Ingress Rule

```yaml
# ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: my-app-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  rules:
  - host: myapp.local
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: my-app-service
            port:
              number: 80
```

```bash
kubectl apply -f ingress.yaml
kubectl get ingress

# Add to /etc/hosts
echo "$(minikube ip) myapp.local" | sudo tee -a /etc/hosts

curl http://myapp.local
```

---

## 🔄 **Chapter 7: Auto-Scaling & Self-Healing**

> 📌 **Keywords**: `HPA`, `HorizontalPodAutoscaler`, `ReadinessProbe`, `LivenessProbe`

---

### ✅ 7.1 Liveness & Readiness Probes

```yaml
# In Deployment spec.containers
livenessProbe:
  httpGet:
    path: /health
    port: 3000
  initialDelaySeconds: 30
  periodSeconds: 10

readinessProbe:
  httpGet:
    path: /ready
    port: 3000
  initialDelaySeconds: 5
  periodSeconds: 5
```

> * **Liveness**: If fails → restart container.
>     
> * **Readiness**: If fails → stop sending traffic.
>     

---

### ✅ 7.2 Horizontal Pod Autoscaler (HPA)

```yaml
# hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: my-app-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: my-app-deployment
  minReplicas: 1
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50
```

```bash
kubectl apply -f hpa.yaml
kubectl get hpa

# Generate load to test
kubectl run -i --tty load-generator --rm --image=busybox --restart=Never -- /bin/sh -c "while sleep 0.01; do wget -q -O- http://my-app-service; done"
```

---

## 🛡️ **Chapter 8: Security & RBAC**

> 📌 **Keywords**: `RBAC`, `ServiceAccount`, `Role`, `ClusterRole`, `RoleBinding`

---

### ✅ 8.1 ServiceAccount + RoleBinding

```yaml
# serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: my-app-sa
```

```yaml
# role.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list"]
```

```yaml
# rolebinding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: default
subjects:
- kind: ServiceAccount
  name: my-app-sa
  namespace: default
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io
```

```yaml
# In Deployment spec
serviceAccountName: my-app-sa
```

---

## 🧰 **Chapter 9: Advanced Tooling — Helm, Kustomize, Operators**

> 📌 **Keywords**: `Helm`, `Chart`, `Kustomize`, `Operator`, `CRD`

---

### ✅ 9.1 Helm — Package Manager for K8s

```bash
# Install Helm
brew install helm

# Add repo
helm repo add bitnami https://charts.bitnami.com/bitnami

# Install chart
helm install my-release bitnami/nginx

# Create your own chart
helm create my-chart
helm install my-app ./my-chart --set image.tag=1.0

# Values override
helm install my-app ./my-chart -f values-prod.yaml
```

---

### ✅ 9.2 Kustomize — Template-Free Configuration

```bash
# Directory structure
base/
  deployment.yaml
  service.yaml
  kustomization.yaml
overlays/
  prod/
    replicas.yaml
    kustomization.yaml
```

```yaml
# base/kustomization.yaml
resources:
- deployment.yaml
- service.yaml
```

```yaml
# overlays/prod/replicas.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app-deployment
spec:
  replicas: 5
```

```yaml
# overlays/prod/kustomization.yaml
resources:
- ../../base
patchesStrategicMerge:
- replicas.yaml
```

```bash
kubectl apply -k overlays/prod
```

---

### ✅ 9.3 Operator Pattern — Automate Complex Apps

> Use **Operator SDK** or **Kubebuilder** to create custom controllers for stateful apps (DBs, Kafka, etc).

```yaml
# Example: etcd-operator
apiVersion: etcd.database.coreos.com/v1beta2
kind: EtcdCluster
metadata:
  name: my-etcd
spec:
  size: 3
  version: 3.5.0
```

---

## 🚀 **Chapter 10: CI/CD, GitOps & Production**

> 📌 **Keywords**: `GitOps`, `ArgoCD`, `Flux`, `CI/CD`, `Jenkins`, `GitHub Actions`, `Production`, `Monitoring`, `Prometheus`, `Grafana`, `Logging`, `EFK`, `Loki`

---

### ✅ 10.1 GitOps with ArgoCD

```bash
# Install ArgoCD
kubectl create namespace argocd
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

# Get password
kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d

# Port forward
kubectl port-forward svc/argocd-server -n argocd 8080:443

# Login at https://localhost:8080 → user: admin, password: <above>
```

> Create App in UI pointing to your Git repo with K8s manifests.

---

### ✅ 10.2 GitHub Actions CI/CD

```yaml
# .github/workflows/deploy.yaml
name: Deploy to Kubernetes

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4

    - name: Build and push Docker image
      run: |
        docker build -t ${{ secrets.DOCKERHUB_USERNAME }}/my-app:${{ github.sha }} .
        echo ${{ secrets.DOCKERHUB_TOKEN }} | docker login -u ${{ secrets.DOCKERHUB_USERNAME }} --password-stdin
        docker push ${{ secrets.DOCKERHUB_USERNAME }}/my-app:${{ github.sha }}

    - name: Deploy to Kubernetes
      run: |
        kubectl set image deployment/my-app-deployment my-app=${{ secrets.DOCKERHUB_USERNAME }}/my-app:${{ github.sha }}
      env:
        KUBE_CONFIG_DATA: ${{ secrets.KUBE_CONFIG_DATA }}
```

---

### ✅ 10.3 Production Checklist

| Area | Tool/Practice |
| --- | --- |
| Monitoring | Prometheus + Grafana |
| Logging | Loki + Promtail or EFK (Elasticsearch, Fluentd, Kibana) |
| Tracing | Jaeger, OpenTelemetry |
| Security | RBAC, Network Policies, Pod Security Admission, OPA/Gatekeeper |
| Backups | Velero |
| Ingress | NGINX Ingress + Cert-Manager (Let’s Encrypt) |
| Secrets | HashiCorp Vault / External Secrets |
| CI/CD | ArgoCD (GitOps) or Flux |

---

## 🧪 **Chapter 11: Debugging & Troubleshooting**

```bash
# Common Commands
kubectl get all
kubectl describe pod <pod-name>
kubectl logs <pod-name> -f
kubectl exec -it <pod-name> -- /bin/sh
kubectl port-forward <pod-name> 3000:3000
kubectl get events --sort-by='.metadata.creationTimestamp'

# Debugging CrashLoopBackOff
kubectl describe pod <pod>  # Check Events
kubectl logs <pod> --previous  # Previous container logs

# Network Debugging
kubectl run debug --image=nicolaka/netshoot --rm -it -- bash
curl my-app-service
dig my-app-service
```

---

## 🎓 **Final Project: Full-Stack App on Kubernetes**

> ✅ React Frontend + Node.js Backend + PostgreSQL + Redis

```yaml
# Full structure
.
├── frontend/
│   ├── Dockerfile
│   └── deployment.yaml
├── backend/
│   ├── Dockerfile
│   └── deployment.yaml
├── postgres/
│   ├── statefulset.yaml
│   └── pvc.yaml
├── redis/
│   └── deployment.yaml
├── ingress.yaml
└── kustomization.yaml
```

> ✅ Apply with `kubectl apply -k .`

---

## ✅ **Kubernetes Mastery Checklist**

| Skill | ✅ |
| --- | --- |
| Set up local cluster (Minikube/Kind) | ✔️ |
| Containerize app with Docker | ✔️ |
| Deploy Pods, Deployments, Services | ✔️ |
| Use ConfigMap & Secret | ✔️ |
| Configure Persistent Storage | ✔️ |
| Route traffic with Ingress | ✔️ |
| Auto-scale with HPA | ✔️ |
| Add health probes | ✔️ |
| Secure with RBAC | ✔️ |
| Package with Helm/Kustomize | ✔️ |
| Implement GitOps (ArgoCD) | ✔️ |
| Set up CI/CD | ✔️ |
| Monitor with Prometheus/Grafana | ✔️ |
| Troubleshoot common issues | ✔️ |

---

# Q&A

---

## 🧱 **CHAPTER 1: CORE CONCEPTS & ARCHITECTURE**

### Q1: What is Kubernetes? Why use it?

> **Answer**:  
> Kubernetes (K8s) is an **open-source container orchestration platform** for automating deployment, scaling, and management of containerized applications.
> 
> **Why Kubernetes?**
> 
> * ✅ **Auto-healing**: Restarts failed containers.
>     
> * ✅ **Auto-scaling**: Scale up/down based on load.
>     
> * ✅ **Service Discovery & Load Balancing**: Built-in networking.
>     
> * ✅ **Declarative Configuration**: Define desired state → K8s reconciles.
>     
> * ✅ **Multi-cloud & Hybrid**: Runs anywhere — AWS, GCP, Azure, On-Prem.
>     
> * ✅ **Ecosystem**: Helm, Operators, Prometheus, ArgoCD, Istio, etc.
>     
> 
> 💡 *Analogy*: Kubernetes is like an **air traffic control system** for containers — it schedules, routes, heals, and scales your “flights” (containers).

---

### Q2: What are the main components of Kubernetes architecture?

> **Answer**:  
> Kubernetes has a **control plane** (master) and **worker nodes**:
> 
> **Control Plane**:
> 
> * `kube-apiserver`: Frontend — validates & processes REST requests.
>     
> * `etcd`: Distributed key-value store — holds cluster state.
>     
> * `kube-scheduler`: Assigns Pods to Nodes.
>     
> * `kube-controller-manager`: Runs controllers (Node, ReplicaSet, etc.).
>     
> * `cloud-controller-manager`: Integrates with cloud providers.
>     
> 
> **Worker Node**:
> 
> * `kubelet`: Agent — ensures containers run in Pod.
>     
> * `kube-proxy`: Maintains network rules → enables Service abstraction.
>     
> * `Container Runtime`: Docker, containerd, CRI-O.
>     
> 
> 🖼️ *Architecture Diagram*:
> 
> ```plaintext
> [User] → kube-apiserver → etcd  
>                ↓  
>        kube-scheduler → kubelet (on Nodes)  
>                ↓  
>        kube-controller-manager
> ```

---

### Q3: What is a Pod? Why is it the smallest unit?

> **Answer**:  
> A **Pod** is the smallest deployable unit in Kubernetes — it can contain **one or more containers** that share:
> 
> * Network namespace (same IP, port space)
>     
> * Storage volumes
>     
> * IPC (inter-process communication)
>     
> 
> ✅ **Use Cases**:
> 
> * App + logging sidecar
>     
> * App + proxy (e.g., Istio sidecar)
>     
> 
> ⚠️ **Never manage Pods directly** — use **Deployments** or **StatefulSets**. Pods are ephemeral.

> 💡 *Analogy*: A Pod is like a **shared apartment** — containers are roommates sharing kitchen (storage) and Wi-Fi (network).

---

## 🐳 **CHAPTER 2: DOCKER & CONTAINER INTEGRATION**

### Q4: How does Docker work with Kubernetes?

> **Answer**:  
> Kubernetes doesn’t build containers — it **runs** them.
> 
> ✅ **Workflow**:
> 
> 1. Write `Dockerfile` → `docker build -t my-app:1.0 .`
>     
> 2. Push to registry: `docker push my-registry/my-app:1.0`
>     
> 3. Reference in Pod spec: `image: my-registry/my-app:1.0`
>     
> 
> ⚠️ **Local Dev Tip**:
> 
> * Minikube: `minikube image load my-app:1.0`
>     
> * Kind: `kind load docker-image my-app:1.0 --name cluster-name`
>     
> 
> ❌ **Never use** `latest` tag in production — use immutable tags (e.g., `v1.2.3`, `git-sha`).

---

### Q5: What is a container runtime? Which ones does Kubernetes support?

> **Answer**:  
> Container runtime runs containers on Nodes. Kubernetes supports any **CRI (Container Runtime Interface)**\-compatible runtime:
> 
> * `containerd` (default in most clusters)
>     
> * `CRI-O` (lightweight, OpenShift default)
>     
> * `Docker` (via `dockershim`, deprecated in 1.24+)
>     
> 
> ✅ **Check runtime**:
> 
> ```bash
> kubectl get nodes -o wide  # Look at CONTAINER-RUNTIME column
> ```

---

## 🧩 **CHAPTER 3: DEPLOYMENTS, SERVICES & NETWORKING**

### Q6: What is a Deployment? How is it different from a Pod?

> **Answer**:
> 
> * **Pod**: Single instance — ephemeral.
>     
> * **Deployment**: Manages a **ReplicaSet** → ensures desired number of **identical Pods** are running → supports rolling updates, rollbacks.
>     
> 
> ✅ **Use Deployment for stateless apps**.  
> ✅ **Use StatefulSet for stateful apps** (DBs, Kafka).
> 
> Example:
> 
> ```yaml
> apiVersion: apps/v1
> kind: Deployment
> metadata:
>   name: nginx-deploy
> spec:
>   replicas: 3
>   selector:
>     matchLabels:
>       app: nginx
>   template:
>     metadata:
>       labels:
>         app: nginx
>     spec:
>       containers:
>       - name: nginx
>         image: nginx:1.25
> ```

---

### Q7: What are the types of Services in Kubernetes?

> **Answer**:
> 
> | Type | Use Case | Access |
> | --- | --- | --- |
> | `ClusterIP` | Internal communication | Only within cluster |
> | `NodePort` | Dev/testing, external via Node IP:Port | `<NodeIP>:<NodePort>` |
> | `LoadBalancer` | Cloud production | External IP (from cloud provider) |
> | `ExternalName` | Route to external DNS | CNAME record |
> 
> ✅ **Production**: Use `LoadBalancer` or `Ingress` (not NodePort).  
> ✅ **Internal Apps**: Use `ClusterIP`.

---

### Q8: What is an Ingress? How is it different from a Service?

> **Answer**:
> 
> * **Service**: Exposes Pods → Layer 4 (TCP/UDP).
>     
> * **Ingress**: Exposes HTTP/HTTPS routes → Layer 7. Requires **Ingress Controller** (NGINX, Traefik, AWS ALB).
>     
> 
> Example:
> 
> ```yaml
> apiVersion: networking.k8s.io/v1
> kind: Ingress
> metadata:
>   name: app-ingress
>   annotations:
>     nginx.ingress.kubernetes.io/rewrite-target: /
> spec:
>   ingressClassName: nginx
>   rules:
>   - host: myapp.com
>     http:
>       paths:
>       - path: /
>         pathType: Prefix
>         backend:
>           service:
>             name: my-service
>             port:
>               number: 80
> ```
> 
> ✅ **Ingress = HTTP Router + Load Balancer + SSL Terminator**.

---

## 🗃️ **CHAPTER 4: CONFIG, SECRETS & STORAGE**

### Q9: What is a ConfigMap? How to use it?

> **Answer**:  
> `ConfigMap` stores **non-sensitive configuration** (env vars, config files).
> 
> ✅ **Ways to inject**:
> 
> * Env vars
>     
> * Volume mounts (for config files)
>     
> 
> Example:
> 
> ```yaml
> apiVersion: v1
> kind: ConfigMap
> metadata:
>   name: app-config
> data:
>   LOG_LEVEL: info
>   CONFIG_FILE: |
>     server:
>       port: 3000
> ```
> 
> In Deployment:
> 
> ```yaml
> envFrom:
> - configMapRef:
>     name: app-config
> volumeMounts:
> - name: config-volume
>   mountPath: /etc/config
> volumes:
> - name: config-volume
>   configMap:
>     name: app-config
> ```

---

### Q10: What is a Secret? Is it secure?

> **Answer**:  
> `Secret` stores **sensitive data** (passwords, tokens, keys).
> 
> ❌ **Not encrypted by default** — stored as base64 in etcd.  
> ✅ **Secure in Production**:
> 
> * Enable **Encryption at Rest** (kube-apiserver flag).
>     
> * Use **HashiCorp Vault**, **SealedSecrets**, or **External Secrets Operator**.
>     
> 
> Example:
> 
> ```bash
> kubectl create secret generic db-secret \
>   --from-literal=DB_PASSWORD=supersecret
> ```
> 
> Inject like ConfigMap.

---

### Q11: What is PersistentVolume (PV) and PersistentVolumeClaim (PVC)?

> **Answer**:
> 
> * **PV**: Cluster resource — physical storage (NFS, EBS, local disk).
>     
> * **PVC**: Request for storage by a Pod → binds to PV.
>     
> 
> ✅ **Dynamic Provisioning**: PVC → StorageClass → auto-creates PV.
> 
> Example:
> 
> ```yaml
> # PVC
> apiVersion: v1
> kind: PersistentVolumeClaim
> metadata:
>   name: my-pvc
> spec:
>   accessModes: [ReadWriteOnce]
>   resources:
>     requests:
>       storage: 1Gi
>   storageClassName: standard
> ```
> 
> In Pod:
> 
> ```yaml
> volumeMounts:
> - name: data
>   mountPath: /data
> volumes:
> - name: data
>   persistentVolumeClaim:
>     claimName: my-pvc
> ```

---

## 🔄 **CHAPTER 5: SCALING, AUTO-HEALING & UPGRADES**

### Q12: What are Liveness, Readiness, and Startup Probes?

> **Answer**:
> 
> * **Liveness Probe**: Is app alive? → If fails → **restart container**.
>     
> * **Readiness Probe**: Is app ready to serve traffic? → If fails → **remove from Service endpoints**.
>     
> * **Startup Probe**: Is app started? → Disables liveness/readiness until success (for slow-start apps).
>     
> 
> Example:
> 
> ```yaml
> livenessProbe:
>   httpGet:
>     path: /health
>     port: 8080
>   initialDelaySeconds: 30
>   periodSeconds: 10
> readinessProbe:
>   httpGet:
>     path: /ready
>     port: 8080
>   initialDelaySeconds: 5
>   periodSeconds: 5
> ```

---

### Q13: How does Horizontal Pod Autoscaler (HPA) work?

> **Answer**:  
> HPA scales **number of Pods** based on metrics (CPU, memory, custom).
> 
> ✅ **Requires Metrics Server** installed.
> 
> Example:
> 
> ```yaml
> apiVersion: autoscaling/v2
> kind: HorizontalPodAutoscaler
> metadata:
>   name: my-app-hpa
> spec:
>   scaleTargetRef:
>     apiVersion: apps/v1
>     kind: Deployment
>     name: my-app
>   minReplicas: 1
>   maxReplicas: 10
>   metrics:
>   - type: Resource
>     resource:
>       name: cpu
>       target:
>         type: Utilization
>         averageUtilization: 50
> ```
> 
> 📈 **Test**: Generate load → `kubectl get hpa -w`

---

### Q14: What is a Rolling Update? How to rollback?

> **Answer**:  
> **Rolling Update**: Gradually replaces old Pods with new ones → zero downtime.
> 
> ✅ **Strategy in Deployment**:
> 
> ```yaml
> strategy:
>   type: RollingUpdate
>   rollingUpdate:
>     maxSurge: 25%
>     maxUnavailable: 25%
> ```
> 
> ✅ **Rollback**:
> 
> ```bash
> kubectl rollout history deployment/my-app
> kubectl rollout undo deployment/my-app --to-revision=2
> ```

---

## 🛡️ **CHAPTER 6: SECURITY & RBAC**

### Q15: What is RBAC in Kubernetes?

> **Answer**:  
> **Role-Based Access Control (RBAC)** restricts access to cluster resources.
> 
> ✅ **Key Objects**:
> 
> * `ServiceAccount`: Identity for Pods.
>     
> * `Role` / `ClusterRole`: Permissions (namespace/cluster-scoped).
>     
> * `RoleBinding` / `ClusterRoleBinding`: Grants role to user/SA.
>     
> 
> Example:
> 
> ```yaml
> apiVersion: rbac.authorization.k8s.io/v1
> kind: Role
> metadata:
>   namespace: default
>   name: pod-reader
> rules:
> - apiGroups: [""]
>   resources: ["pods"]
>   verbs: ["get", "watch", "list"]
> ---
> apiVersion: rbac.authorization.k8s.io/v1
> kind: RoleBinding
> metadata:
>   name: read-pods
>   namespace: default
> subjects:
> - kind: ServiceAccount
>   name: my-app-sa
>   namespace: default
> roleRef:
>   kind: Role
>   name: pod-reader
>   apiGroup: rbac.authorization.k8s.io
> ```

---

### Q16: What are Network Policies? Why use them?

> **Answer**:  
> `NetworkPolicy` controls **Pod-to-Pod traffic** (like a firewall).
> 
> ✅ **Requires CNI plugin support** (Calico, Cilium, Weave).
> 
> Example: Allow only frontend Pods to talk to backend.
> 
> ```yaml
> apiVersion: networking.k8s.io/v1
> kind: NetworkPolicy
> metadata:
>   name: backend-allow-frontend
> spec:
>   podSelector:
>     matchLabels:
>       app: backend
>   ingress:
>   - from:
>     - podSelector:
>         matchLabels:
>           app: frontend
>     ports:
>     - protocol: TCP
>       port: 8080
> ```

---

## 🧰 **CHAPTER 7: ADVANCED TOOLING — HELM, KUSTOMIZE, OPERATORS**

### Q17: What is Helm? What is a Chart?

> **Answer**:  
> **Helm** = Package manager for Kubernetes.  
> **Chart** = Pre-configured K8s app (templates + values).
> 
> ✅ **Structure**:
> 
> ```plaintext
> my-chart/
> ├── Chart.yaml
> ├── values.yaml
> ├── templates/
> │   ├── deployment.yaml
> │   └── service.yaml
> └── charts/ (dependencies)
> ```
> 
> ✅ **Commands**:
> 
> ```bash
> helm install my-release bitnami/nginx
> helm upgrade my-release ./my-chart --set image.tag=2.0
> helm rollback my-release 1
> helm list
> ```

---

### Q18: What is Kustomize? How is it different from Helm?

> **Answer**:
> 
> | Helm | Kustomize |
> | --- | --- |
> | Uses templates (Go text/template) | Template-free — patches YAML |
> | Values override | Strategic merge patches |
> | Complex, powerful | Simple, GitOps-friendly |
> | Charts in repos | Plain YAML in your repo |
> 
> ✅ **Kustomize Example**:
> 
> ```yaml
> # overlays/prod/kustomization.yaml
> resources:
> - ../../base
> patchesStrategicMerge:
> - replicas.yaml
> namePrefix: prod-
> ```
> 
> Apply: `kubectl apply -k overlays/prod`

---

### Q19: What is an Operator? When to use it?

> **Answer**:  
> **Operator** = Software that **automates complex stateful apps** (DBs, Kafka, Prometheus) using **Custom Resources (CRDs)**.
> 
> ✅ **Use when**:
> 
> * App needs lifecycle management (backup, upgrade, failover).
>     
> * Beyond what Deployment/StatefulSet offers.
>     
> 
> Example: `etcd-operator`, `prometheus-operator`.
> 
> ✅ **Build with**: Operator SDK, Kubebuilder.

---

## 🚀 **CHAPTER 8: CI/CD, GITOPS & PRODUCTION**

### Q20: What is GitOps? How does ArgoCD work?

> **Answer**:  
> **GitOps** = Manage infrastructure/apps via Git → single source of truth.
> 
> **ArgoCD** = GitOps tool — continuously syncs cluster state with Git repo.
> 
> ✅ **Workflow**:
> 
> 1. Push K8s manifests to Git.
>     
> 2. ArgoCD detects drift → auto-applies changes.
>     
> 3. Rollback = `git revert`.
>     
> 
> ✅ **Install**:
> 
> ```bash
> kubectl create namespace argocd
> kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
> kubectl port-forward svc/argocd-server -n argocd 8080:443
> ```

---

### Q21: How to set up CI/CD for Kubernetes?

> **Answer**:  
> ✅ **Options**:
> 
> * **GitOps (ArgoCD/Flux)**: Sync from Git → best for production.
>     
> * **CI Pipeline (GitHub Actions, Jenkins)**: Build → Push Image → `kubectl apply` or `helm upgrade`.
>     
> 
> Example GitHub Actions:
> 
> ```yaml
> - name: Deploy to K8s
>   run: |
>     kubectl set image deployment/my-app my-app=${{ secrets.REGISTRY }}/my-app:${{ github.sha }}
>   env:
>     KUBE_CONFIG_DATA: ${{ secrets.KUBE_CONFIG }}
> ```

---

## 🧪 **CHAPTER 9: TROUBLESHOOTING & DEBUGGING**

### Q22: How to debug a Pod in CrashLoopBackOff?

> **Answer**:  
> ✅ **Steps**:
> 
> 1. `kubectl describe pod <pod-name>` → check Events.
>     
> 2. `kubectl logs <pod-name> --previous` → logs from previous container.
>     
> 3. `kubectl exec -it <pod-name> -- /bin/sh` → inspect filesystem.
>     
> 4. Check resource limits, config, secrets, liveness probes.
>     
> 
> ✅ **Common Causes**:
> 
> * Missing ConfigMap/Secret.
>     
> * Wrong image/command.
>     
> * Liveness probe failing.
>     
> * Resource limits exceeded.
>     

---

### Q23: How to check why a Service isn’t routing traffic?

> **Answer**:  
> ✅ **Steps**:
> 
> 1. `kubectl get endpoints <service-name>` → are Pods listed?
>     
> 2. Check Pod labels match Service selector.
>     
> 3. Check Pod `readinessProbe` — if failing, Pod excluded from endpoints.
>     
> 4. `kubectl get svc` → correct ClusterIP/Port.
>     
> 5. Test from within cluster: `kubectl run debug --image=busybox --rm -it -- wget -O- http://<service-name>`
>     

---

### Q24: What are common kubectl commands for debugging?

> **Answer**:
> 
> ```bash
> kubectl get all                          # Get all resources
> kubectl describe <resource> <name>       # Detailed info + events
> kubectl logs <pod> -f                   # Stream logs
> kubectl logs <pod> --previous           # Previous container logs
> kubectl exec -it <pod> -- /bin/sh       # Enter container
> kubectl port-forward <pod> 8080:80      # Forward local port
> kubectl get events --sort-by='.metadata.creationTimestamp'
> kubectl top pod                         # Resource usage (needs metrics-server)
> ```

---

## 🎓 **CHAPTER 10: ADVANCED & INTERVIEW DEEP DIVES**

### Q25: What is a StatefulSet? When to use it?

> **Answer**:  
> `StatefulSet` manages **stateful apps** (DBs, Kafka, ZooKeeper) with:
> 
> * Stable network IDs (`pod-0`, `pod-1`).
>     
> * Stable storage (PVC per Pod).
>     
> * Ordered deployment/rollback.
>     
> 
> ✅ **Use for**: Databases, distributed systems requiring stable identity.  
> ✅ **Don’t use for**: Stateless apps → use Deployment.

---

### Q26: What is a DaemonSet? Use cases?

> **Answer**:  
> `DaemonSet` ensures **one Pod runs on every (or selected) Node**.
> 
> ✅ **Use Cases**:
> 
> * Logging agents (Fluentd, Logstash).
>     
> * Monitoring agents (Prometheus Node Exporter).
>     
> * Network plugins (Calico, Cilium).
>     
> 
> Example:
> 
> ```yaml
> apiVersion: apps/v1
> kind: DaemonSet
> metadata:
>   name: fluentd
> spec:
>   selector:
>     matchLabels:
>       name: fluentd
>   template:
>     metadata:
>       labels:
>         name: fluentd
>     spec:
>       containers:
>       - name: fluentd
>         image: fluentd
> ```

---

### Q27: What is a Job and CronJob?

> **Answer**:
> 
> * **Job**: Runs a Pod to **completion** (e.g., batch job, migration).
>     
> * **CronJob**: Runs Jobs on a **schedule** (e.g., daily backup).
>     
> 
> Example CronJob:
> 
> ```yaml
> apiVersion: batch/v1
> kind: CronJob
> metadata:
>   name: backup
> spec:
>   schedule: "0 * * * *"  # Hourly
>   jobTemplate:
>     spec:
>       template:
>         spec:
>           containers:
>           - name: backup
>             image: alpine
>             command: ["/bin/sh", "-c", "echo Backing up..."]
>           restartPolicy: OnFailure
> ```

---

### Q28: What is the difference between ConfigMap and Secret?

> **Answer**:
> 
> | ConfigMap | Secret |
> | --- | --- |
> | Non-sensitive data | Sensitive data |
> | Stored as plain text in etcd | Stored as base64 in etcd |
> | No encryption by default | No encryption by default |
> | Can be mounted as env/volume | Can be mounted as env/volume |
> 
> ✅ **Both are NOT secure without etcd encryption or external secrets**.

---

### Q29: What is a Namespace? Why use it?

> **Answer**:  
> `Namespace` isolates resources (Pods, Services, ConfigMaps) within a cluster.
> 
> ✅ **Use Cases**:
> 
> * Environment separation (dev, staging, prod).
>     
> * Team/Project isolation.
>     
> * Resource quotas.
>     
> 
> ✅ **Default Namespaces**: `default`, `kube-system`, `kube-public`.
> 
> Example:
> 
> ```bash
> kubectl create namespace staging
> kubectl apply -f app.yaml -n staging
> ```

---

### Q30: What is kubeconfig? How to manage multiple clusters?

> **Answer**:  
> `kubeconfig` = YAML file (`~/.kube/config`) storing:
> 
> * Cluster endpoints.
>     
> * User credentials.
>     
> * Contexts (cluster + user + namespace).
>     
> 
> ✅ **Commands**:
> 
> ```bash
> kubectl config get-contexts
> kubectl config use-context my-cluster
> kubectl config set-context --current --namespace=staging
> kubectl config view
> ```
> 
> ✅ **Tools**: `kubectx`, `kubens` for easy switching.

---

## 🧠 **BONUS: REAL INTERVIEW QUESTIONS**

### Q31: How does Kubernetes networking work? (CNI, Pod IP, Service IP)

> **Answer**:
> 
> * **Pod IP**: Each Pod gets unique IP → all Pods can communicate directly.
>     
> * **Service IP**: Virtual IP → kube-proxy routes to Pods via iptables/IPVS.
>     
> * **CNI (Container Network Interface)**: Plugin (Calico, Flannel, Cilium) assigns Pod IPs.
>     
> 
> ✅ **Rule**: Pods can talk to any Pod, any Node, any Service — no NAT.

---

### Q32: What is the difference between ReplicaSet and ReplicationController?

> **Answer**:
> 
> * **ReplicationController (RC)**: Legacy — selector uses equality-based labels.
>     
> * **ReplicaSet (RS)**: Modern — supports set-based selectors → used by Deployments.
>     
> 
> ✅ **Never use RC/RS directly** — use **Deployment**.

---

### Q33: What is taint and toleration?

> **Answer**:
> 
> * **Taint**: Applied to Node → repels Pods.
>     
> * **Toleration**: Applied to Pod → allows scheduling on tainted Node.
>     
> 
> ✅ **Use Case**: Dedicate Nodes for specific workloads (e.g., GPU Nodes).
> 
> Example:
> 
> ```bash
> # Taint Node
> kubectl taint nodes node1 key=value:NoSchedule
> 
> # In Pod spec
> tolerations:
> - key: "key"
>   operator: "Equal"
>   value: "value"
>   effect: "NoSchedule"
> ```

---

### Q34: What is affinity and anti-affinity?

> **Answer**:
> 
> * **Affinity**: Attract Pods to Nodes/Pods (e.g., same AZ).
>     
> * **Anti-affinity**: Repel Pods (e.g., spread across Nodes for HA).
>     
> 
> Example: Spread Pods across Nodes:
> 
> ```yaml
> affinity:
>   podAntiAffinity:
>     requiredDuringSchedulingIgnoredDuringExecution:
>     - labelSelector:
>         matchExpressions:
>         - key: app
>           operator: In
>           values: [my-app]
>       topologyKey: kubernetes.io/hostname
> ```

---

### Q35: What is initContainer? Use cases?

> **Answer**:  
> `initContainer` runs **before main containers** → must complete successfully.
> 
> ✅ **Use Cases**:
> 
> * Wait for DB to be ready.
>     
> * Clone git repo.
>     
> * Generate config files.
>     
> 
> Example:
> 
> ```yaml
> initContainers:
> - name: wait-for-db
>   image: busybox
>   command: ['sh', '-c', 'until nc -z db-service 5432; do echo waiting; sleep 2; done;']
> ```

---

## ✅ **KUBERNETES INTERVIEW MASTERY CHECKLIST**

| Topic | ✅ |
| --- | --- |
| Explain K8s architecture | ✔️ |
| Deploy Pods, Deployments, Services | ✔️ |
| Configure Ingress & Networking | ✔️ |
| Use ConfigMap & Secret | ✔️ |
| Set up Persistent Storage | ✔️ |
| Implement Auto-Scaling (HPA) | ✔️ |
| Add Health Probes | ✔️ |
| Secure with RBAC & NetworkPolicy | ✔️ |
| Package with Helm/Kustomize | ✔️ |
| Implement GitOps (ArgoCD) | ✔️ |
| Set up CI/CD pipeline | ✔️ |
| Debug common issues (CrashLoop, Service) | ✔️ |
| Explain advanced workloads (StatefulSet, DaemonSet, Job) | ✔️ |
| Manage multi-cluster/multi-namespace | ✔️ |

---
