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)
# 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
| 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
# 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:
Write
Dockerfileβdocker build -t my-app:1.0 .Push to registry:
docker push my-registry/my-app:1.0Reference in Pod spec:
image: my-registry/my-app:1.0β οΈ Local Dev Tip:
Minikube:
minikube image load my-app:1.0Kind:
kind load docker-image my-app:1.0 --name cluster-nameβ Never use
latesttag 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(viadockershim, 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:
Type Use Case Access ClusterIPInternal communication Only within cluster NodePortDev/testing, external via Node IP:Port <NodeIP>:<NodePort>LoadBalancerCloud production External IP (from cloud provider) ExternalNameRoute to external DNS CNAME record β Production: Use
LoadBalancerorIngress(not NodePort).
β Internal Apps: UseClusterIP.
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:
ConfigMapstores 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: 3000In 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:
Secretstores 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=supersecretInject 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: standardIn 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:
NetworkPolicycontrols 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:
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:
# 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:
Push K8s manifests to Git.
ArgoCD detects drift β auto-applies changes.
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 applyorhelm 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:
kubectl describe pod <pod-name>β check Events.
kubectl logs <pod-name> --previousβ logs from previous container.
kubectl exec -it <pod-name> -- /bin/shβ inspect filesystem.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:
kubectl get endpoints <service-name>β are Pods listed?Check Pod labels match Service selector.
Check Pod
readinessProbeβ if failing, Pod excluded from endpoints.
kubectl get svcβ correct ClusterIP/Port.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:
StatefulSetmanages 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:
DaemonSetensures 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:
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:
Namespaceisolates 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,kubensfor 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:
initContainerruns 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 | βοΈ |



