Skip to main content

Command Palette

Search for a command to run...

Kubernetes: The Complete Guide (With Code & Docker)

Published
β€’25 min read
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?

ProblemKubernetes 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)

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

# 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
FROM node:18-alpine

WORKDIR /app

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

COPY . .

EXPOSE 3000

CMD ["npm", "start"]

βœ… Step 2: Build & Tag

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

βœ… Step 3: Test Locally

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

βœ… Step 4: Push to Registry (Optional for Minikube/Kind)

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

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

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

# service-clusterip.yaml
apiVersion: v1
kind: Service
metadata:
  name: my-app-service
spec:
  selector:
    app: my-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 3000
kubectl apply -f service-clusterip.yaml
kubectl get svc
# Access from within cluster: http://my-app-service

➀ NodePort (External via Node IP)

# 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)
kubectl apply -f service-nodeport.yaml
minikube ip  # Get node IP
curl $(minikube ip):30001

➀ LoadBalancer (Cloud Only)

# service-lb.yaml
apiVersion: v1
kind: Service
metadata:
  name: my-app-lb
spec:
  type: LoadBalancer
  selector:
    app: my-app
  ports:
    - port: 80
      targetPort: 3000
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

# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  APP_NAME: "My Awesome App"
  LOG_LEVEL: "info"
# 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
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

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

# persistentvolumeclaim.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
  storageClassName: standard  # Depends on cluster
# deployment-with-pvc.yaml
volumeMounts:
- name: data-storage
  mountPath: /app/data

volumes:
- name: data-storage
  persistentVolumeClaim:
    claimName: my-pvc
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)

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

βœ… 6.2 Create Ingress Rule

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

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

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

# serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: my-app-sa
# role.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list"]
# 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
# 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

# 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

# Directory structure
base/
  deployment.yaml
  service.yaml
  kustomization.yaml
overlays/
  prod/
    replicas.yaml
    kustomization.yaml
# base/kustomization.yaml
resources:
- deployment.yaml
- service.yaml
# overlays/prod/replicas.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app-deployment
spec:
  replicas: 5
# overlays/prod/kustomization.yaml
resources:
- ../../base
patchesStrategicMerge:
- replicas.yaml
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).

# 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

# 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

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

AreaTool/Practice
MonitoringPrometheus + Grafana
LoggingLoki + Promtail or EFK (Elasticsearch, Fluentd, Kibana)
TracingJaeger, OpenTelemetry
SecurityRBAC, Network Policies, Pod Security Admission, OPA/Gatekeeper
BackupsVelero
IngressNGINX Ingress + Cert-Manager (Let’s Encrypt)
SecretsHashiCorp Vault / External Secrets
CI/CDArgoCD (GitOps) or Flux

πŸ§ͺ Chapter 11: Debugging & Troubleshooting

# 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

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

[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:

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:

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:

TypeUse CaseAccess
ClusterIPInternal communicationOnly within cluster
NodePortDev/testing, external via Node IP:Port<NodeIP>:<NodePort>
LoadBalancerCloud productionExternal IP (from cloud provider)
ExternalNameRoute to external DNSCNAME 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:

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:

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  LOG_LEVEL: info
  CONFIG_FILE: |
    server:
      port: 3000

In Deployment:

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:

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:

# PVC
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-pvc
spec:
  accessModes: [ReadWriteOnce]
  resources:
    requests:
      storage: 1Gi
  storageClassName: standard

In Pod:

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:

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:

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:

strategy:
  type: RollingUpdate
  rollingUpdate:
    maxSurge: 25%
    maxUnavailable: 25%

βœ… Rollback:

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:

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.

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:

my-chart/
β”œβ”€β”€ Chart.yaml
β”œβ”€β”€ values.yaml
β”œβ”€β”€ templates/
β”‚   β”œβ”€β”€ deployment.yaml
β”‚   └── service.yaml
└── charts/ (dependencies)

βœ… Commands:

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:

HelmKustomize
Uses templates (Go text/template)Template-free β€” patches YAML
Values overrideStrategic merge patches
Complex, powerfulSimple, GitOps-friendly
Charts in reposPlain YAML in your repo

βœ… Kustomize Example:

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

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:

- 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:

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:

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:

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:

ConfigMapSecret
Non-sensitive dataSensitive data
Stored as plain text in etcdStored as base64 in etcd
No encryption by defaultNo encryption by default
Can be mounted as env/volumeCan 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:

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:

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:

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

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:

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βœ”οΈ