Learning state
Track this guide
Saved in this browser only. No account required.
Kubernetes Master Class
Engineering-Grade Reference Manual for Kubernetes
A comprehensive guide to Kubernetes (K8s) commands and concepts for container orchestration at scale
Table of Contents
- Core Concepts
- kubectl Basics
- Pod Management
- Deployments & ReplicaSets
- Services & Networking
- ConfigMaps & Secrets
- Volumes & Storage
- Namespaces & Resource Quotas
- StatefulSets & DaemonSets
- Jobs & CronJobs
- Ingress & Load Balancing
- RBAC & Security
- Helm Package Manager
- Troubleshooting & Debugging
- Production Best Practices
Core Concepts
Kubernetes Architecture Overview
Control Plane Components:
- API Server - Frontend for Kubernetes control plane
- etcd - Distributed key-value store for cluster data
- Scheduler - Assigns pods to nodes
- Controller Manager - Runs controller processes
Node Components:
- kubelet - Agent running on each node
- kube-proxy - Network proxy on each node
- Container Runtime - Docker, containerd, or CRI-O
Key Objects:
- Pod - Smallest deployable unit (one or more containers)
- Deployment - Manages ReplicaSets and rolling updates
- Service - Stable network endpoint for pods
- ConfigMap/Secret - Configuration and sensitive data
- Volume - Persistent storage
- Namespace - Virtual cluster for resource isolation
kubectl Basics
๐น Command: kubectl version
โ๏ธ What It Does
Shows the client and server Kubernetes versions.
โ๏ธ Syntax Examples
# Basic: Show version
kubectl version
# Short version
kubectl version --short
# Client version only
kubectl version --client
๐น Command: kubectl cluster-info
โ๏ธ What It Does
Displays cluster information and endpoint URLs.
โ๏ธ Syntax Examples
# Basic: Show cluster info
kubectl cluster-info
# Detailed dump for debugging
kubectl cluster-info dump
๐น Command: kubectl config
โ๏ธ What It Does
Manages kubeconfig files for cluster access and context switching.
โ๏ธ Syntax Examples
# Basic: View current context
kubectl config current-context
# Real-world: List all contexts
kubectl config get-contexts
# Production: Switch context
kubectl config use-context production-cluster
# Set namespace for current context
kubectl config set-context --current --namespace=production
# View full config
kubectl config view
# Add new cluster
kubectl config set-cluster my-cluster --server=https://k8s.example.com
# Set credentials
kubectl config set-credentials admin --token=bearer_token_here
โ๏ธ Notes, Tips & Common Mistakes
- Contexts combine cluster, user, and namespace
- Use
kubectxandkubenstools for easier switching - Keep separate kubeconfig files for different environments
- Never commit kubeconfig files to version control
๐น Command: kubectl get
โ๏ธ What It Does
Lists resources in the cluster. The most frequently used kubectl command.
โ๏ธ Syntax Examples
# Basic: List pods
kubectl get pods
# Real-world: List all resources in namespace
kubectl get all
# Production: Wide output with more details
kubectl get pods -o wide
# List across all namespaces
kubectl get pods --all-namespaces
# or
kubectl get pods -A
# Custom columns
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase
# JSON output
kubectl get pod my-pod -o json
# YAML output
kubectl get pod my-pod -o yaml
# Watch for changes
kubectl get pods -w
# Filter by label
kubectl get pods -l app=nginx
# Sort by creation time
kubectl get pods --sort-by=.metadata.creationTimestamp
โ๏ธ Notes, Tips & Common Mistakes
-o wideshows more details (node, IP)-Aor--all-namespacessearches entire cluster-wwatches for real-time changes-lfilters by labels (key=value)- Use
-o yamlto see full resource definition
๐น Command: kubectl describe
โ๏ธ What It Does
Shows detailed information about a resource, including events.
โ๏ธ Syntax Examples
# Basic: Describe a pod
kubectl describe pod my-pod
# Real-world: Describe deployment
kubectl describe deployment nginx
# Production: Describe node
kubectl describe node worker-1
# Describe service
kubectl describe service my-service
# Describe in specific namespace
kubectl describe pod my-pod -n production
โ๏ธ Notes, Tips & Common Mistakes
- Shows events at the bottom (crucial for debugging)
- More detailed than
kubectl get -o yaml - Use when troubleshooting why pods won't start
- Check "Events" section for errors
๐น Command: kubectl apply / kubectl create
โ๏ธ What It Does
apply- Creates or updates resources (declarative, idempotent)create- Creates new resources only (imperative, fails if exists)
โ๏ธ Syntax Examples
# Basic: Apply from file
kubectl apply -f deployment.yaml
# Real-world: Apply directory of manifests
kubectl apply -f ./k8s-manifests/
# Production: Apply with record for rollback
kubectl apply -f deployment.yaml --record
# Apply from URL
kubectl apply -f https://example.com/manifest.yaml
# Create (imperative)
kubectl create deployment nginx --image=nginx:1.21
# Dry run (test without applying)
kubectl apply -f deployment.yaml --dry-run=client
# Server-side dry run
kubectl apply -f deployment.yaml --dry-run=server
โ๏ธ Notes, Tips & Common Mistakes
- Prefer
applyovercreate(idempotent, can update) --dry-run=clientvalidates locally--dry-run=servervalidates against API server- Use
-f -to read from stdin --recordsaves command in annotations (deprecated but useful)
๐น Command: kubectl delete
โ๏ธ What It Does
Deletes resources from the cluster.
โ๏ธ Syntax Examples
# Basic: Delete by file
kubectl delete -f deployment.yaml
# Real-world: Delete by name
kubectl delete deployment nginx
# Production: Delete with grace period
kubectl delete pod my-pod --grace-period=30
# Force delete (immediate)
kubectl delete pod my-pod --force --grace-period=0
# Delete all pods with label
kubectl delete pods -l app=nginx
# Delete all resources in namespace
kubectl delete all --all -n test-namespace
โ๏ธ Notes, Tips & Common Mistakes
- Default grace period is 30 seconds
--forceshould be last resort (can cause issues)- Deleting deployment also deletes pods
- Use labels for bulk operations carefully
--allis dangerous in production
Pod Management
๐น Understanding Pods
โ๏ธ What They Are
Pods are the smallest deployable units in Kubernetes, containing one or more containers that share network and storage.
โ๏ธ Basic Pod YAML
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
app: nginx
env: production
spec:
containers:
- name: nginx
image: nginx:1.21
ports:
- containerPort: 80
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
env:
- name: ENVIRONMENT
value: "production"
๐น Command: kubectl run
โ๏ธ What It Does
Creates and runs a pod (quick way to test images).
โ๏ธ Syntax Examples
# Basic: Run simple pod
kubectl run nginx --image=nginx
# Real-world: Run with port and labels
kubectl run nginx --image=nginx:1.21 --port=80 --labels=app=web
# Production: Run with resource limits
kubectl run nginx --image=nginx \
--requests='cpu=100m,memory=256Mi' \
--limits='cpu=200m,memory=512Mi'
# Run interactive pod
kubectl run -it busybox --image=busybox --rm -- sh
# Dry run to generate YAML
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml
โ๏ธ Notes, Tips & Common Mistakes
--rmdeletes pod after exit (useful for testing)-itfor interactive terminal- Use
--dry-run=client -o yamlto generate manifests - Prefer Deployments over bare pods in production
๐น Command: kubectl logs
โ๏ธ What It Does
Retrieves logs from containers in pods.
โ๏ธ Syntax Examples
# Basic: Get pod logs
kubectl logs my-pod
# Real-world: Follow logs in real-time
kubectl logs -f my-pod
# Production: Logs from specific container in multi-container pod
kubectl logs my-pod -c nginx
# Previous container instance (after crash)
kubectl logs my-pod --previous
# Last 100 lines
kubectl logs my-pod --tail=100
# Logs since timestamp
kubectl logs my-pod --since=1h
# All pods with label
kubectl logs -l app=nginx --all-containers=true
โ๏ธ Notes, Tips & Common Mistakes
-ffollows logs (liketail -f)--previousshows logs from crashed container-crequired for multi-container pods- Logs are lost when pod is deleted (use logging solution)
๐น Command: kubectl exec
โ๏ธ What It Does
Executes commands inside a running container.
โ๏ธ Syntax Examples
# Basic: Execute single command
kubectl exec my-pod -- ls /app
# Real-world: Interactive shell
kubectl exec -it my-pod -- /bin/bash
# Production: Execute in specific container
kubectl exec -it my-pod -c nginx -- /bin/sh
# Run command with environment variable
kubectl exec my-pod -- env
# Execute as specific user
kubectl exec my-pod -- su - appuser -c "whoami"
โ๏ธ Notes, Tips & Common Mistakes
-itrequired for interactive sessions- Use
/bin/shif/bin/bashnot available --separates kubectl args from command args-cspecifies container in multi-container pod
๐น Command: kubectl port-forward
โ๏ธ What It Does
Forwards local port to a port on a pod (useful for debugging).
โ๏ธ Syntax Examples
# Basic: Forward local port 8080 to pod port 80
kubectl port-forward pod/my-pod 8080:80
# Real-world: Forward to service
kubectl port-forward service/my-service 8080:80
# Production: Forward to deployment
kubectl port-forward deployment/nginx 8080:80
# Bind to specific address
kubectl port-forward --address 0.0.0.0 pod/my-pod 8080:80
โ๏ธ Notes, Tips & Common Mistakes
- Format:
LOCAL_PORT:POD_PORT - Only for debugging, not production access
- Runs in foreground (Ctrl+C to stop)
- Can forward to pod, service, or deployment
๐น Command: kubectl cp
โ๏ธ What It Does
Copies files between local system and pods.
โ๏ธ Syntax Examples
# Basic: Copy from pod to local
kubectl cp my-pod:/app/config.json ./config.json
# Real-world: Copy to pod
kubectl cp ./local-file.txt my-pod:/tmp/
# Production: Copy from specific container
kubectl cp my-pod:/logs/app.log ./app.log -c nginx
# Copy entire directory
kubectl cp my-pod:/app/data ./backup/
โ๏ธ Notes, Tips & Common Mistakes
- Requires
tarin container - Not suitable for large files
- Use volumes for persistent data
-cspecifies container in multi-container pod
Deployments & ReplicaSets
๐น Understanding Deployments
โ๏ธ What They Are
Deployments manage ReplicaSets and provide declarative updates, rolling updates, and rollback capabilities.
โ๏ธ Deployment YAML Example
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.21
ports:
- containerPort: 80
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 200m
memory: 256Mi
livenessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 5
periodSeconds: 5
๐น Command: kubectl create deployment
โ๏ธ What It Does
Creates a deployment (imperative method).
โ๏ธ Syntax Examples
# Basic: Create deployment
kubectl create deployment nginx --image=nginx
# Real-world: Create with replicas
kubectl create deployment nginx --image=nginx:1.21 --replicas=3
# Production: Generate YAML for customization
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > deployment.yaml
๐น Command: kubectl scale
โ๏ธ What It Does
Scales deployments, replicasets, or statefulsets.
โ๏ธ Syntax Examples
# Basic: Scale deployment
kubectl scale deployment nginx --replicas=5
# Real-world: Scale based on current replicas
kubectl scale deployment nginx --current-replicas=3 --replicas=5
# Production: Autoscale based on CPU
kubectl autoscale deployment nginx --min=2 --max=10 --cpu-percent=80
โ๏ธ Notes, Tips & Common Mistakes
- Scaling is immediate
- Use HorizontalPodAutoscaler for automatic scaling
--current-replicasprovides safety check- Scaling down may terminate pods immediately
๐น Command: kubectl rollout
โ๏ธ What It Does
Manages deployment rollouts, updates, and rollbacks.
โ๏ธ Syntax Examples
# Basic: Check rollout status
kubectl rollout status deployment/nginx
# Real-world: View rollout history
kubectl rollout history deployment/nginx
# Production: Rollback to previous version
kubectl rollout undo deployment/nginx
# Rollback to specific revision
kubectl rollout undo deployment/nginx --to-revision=2
# Pause rollout
kubectl rollout pause deployment/nginx
# Resume rollout
kubectl rollout resume deployment/nginx
# Restart deployment (recreate pods)
kubectl rollout restart deployment/nginx
โ๏ธ Notes, Tips & Common Mistakes
restartis useful for picking up ConfigMap changespauseallows testing before full rollout- Use
--recordwith apply to track changes in history - Rollback is quick and safe
๐น Command: kubectl set image
โ๏ธ What It Does
Updates container image in a deployment (triggers rolling update).
โ๏ธ Syntax Examples
# Basic: Update image
kubectl set image deployment/nginx nginx=nginx:1.22
# Real-world: Update multiple containers
kubectl set image deployment/app web=app:v2 cache=redis:6
# Production: Update and record
kubectl set image deployment/nginx nginx=nginx:1.22 --record
โ๏ธ Notes, Tips & Common Mistakes
- Format:
container_name=new_image:tag - Triggers rolling update automatically
- Use
rollout statusto monitor progress - Always specify image tags (avoid
:latest)
Services & Networking
๐น Understanding Services
โ๏ธ Service Types
- ClusterIP (default) - Internal cluster access only
- NodePort - Exposes on each node's IP at static port
- LoadBalancer - Cloud provider load balancer
- ExternalName - Maps to external DNS name
โ๏ธ Service YAML Example
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
type: ClusterIP
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
๐น Command: kubectl expose
โ๏ธ What It Does
Creates a service for existing pods, deployments, or replicasets.
โ๏ธ Syntax Examples
# Basic: Expose deployment as ClusterIP
kubectl expose deployment nginx --port=80
# Real-world: Expose as NodePort
kubectl expose deployment nginx --type=NodePort --port=80
# Production: Expose as LoadBalancer
kubectl expose deployment nginx --type=LoadBalancer --port=80 --target-port=8080
# Expose with specific name
kubectl expose deployment nginx --name=nginx-service --port=80
โ๏ธ Notes, Tips & Common Mistakes
--portis service port,--target-portis container port- Default type is ClusterIP
- LoadBalancer requires cloud provider support
- Service selector must match pod labels
๐น Command: kubectl get endpoints
โ๏ธ What It Does
Shows endpoints (pod IPs) backing a service.
โ๏ธ Syntax Examples
# Basic: List all endpoints
kubectl get endpoints
# Real-world: Describe specific endpoint
kubectl describe endpoints nginx-service
# Check if service has endpoints
kubectl get endpoints nginx-service
โ๏ธ Notes, Tips & Common Mistakes
- Empty endpoints means no matching pods
- Check selectors if endpoints are missing
- Useful for debugging service connectivity
ConfigMaps & Secrets
๐น Command: kubectl create configmap
โ๏ธ What It Does
Creates ConfigMaps to store non-sensitive configuration data.
โ๏ธ Syntax Examples
# Basic: Create from literal values
kubectl create configmap app-config --from-literal=ENV=production
# Real-world: Create from file
kubectl create configmap nginx-config --from-file=nginx.conf
# Production: Create from directory
kubectl create configmap app-configs --from-file=./configs/
# Create from env file
kubectl create configmap app-env --from-env-file=.env
โ๏ธ ConfigMap YAML Example
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
database_url: "postgres://db:5432/myapp"
log_level: "info"
config.json: |
{
"feature_flags": {
"new_ui": true
}
}
โ๏ธ Using ConfigMap in Pod
spec:
containers:
- name: app
image: myapp:latest
envFrom:
- configMapRef:
name: app-config
# Or mount as volume
volumeMounts:
- name: config
mountPath: /etc/config
volumes:
- name: config
configMap:
name: app-config
๐น Command: kubectl create secret
โ๏ธ What It Does
Creates Secrets to store sensitive data (passwords, tokens, keys).
โ๏ธ Syntax Examples
# Basic: Create generic secret
kubectl create secret generic db-password --from-literal=password=mysecret
# Real-world: Create from file
kubectl create secret generic tls-cert --from-file=tls.crt --from-file=tls.key
# Production: Create TLS secret
kubectl create secret tls my-tls-secret --cert=tls.crt --key=tls.key
# Docker registry secret
kubectl create secret docker-registry regcred \
--docker-server=myregistry.io \
--docker-username=user \
--docker-password=pass \
--docker-email=user@example.com
โ๏ธ Secret YAML Example
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
type: Opaque
data:
username: YWRtaW4= # base64 encoded
password: cGFzc3dvcmQ= # base64 encoded
โ๏ธ Using Secret in Pod
spec:
containers:
- name: app
image: myapp:latest
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-credentials
key: password
โ๏ธ Notes, Tips & Common Mistakes
- Secrets are base64 encoded, NOT encrypted
- Use external secret managers (Vault, AWS Secrets Manager) for production
- Never commit secrets to version control
- Limit RBAC access to secrets
Volumes & Storage
๐น Understanding Volumes
โ๏ธ Volume Types
- emptyDir - Temporary, deleted with pod
- hostPath - Mounts from node filesystem (avoid in production)
- persistentVolumeClaim - Requests persistent storage
- configMap/secret - Mounts config/secrets as files
- nfs, cephfs, etc. - Network storage
โ๏ธ PersistentVolume (PV) Example
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv-data
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: standard
hostPath:
path: /mnt/data
โ๏ธ PersistentVolumeClaim (PVC) Example
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: pvc-data
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5Gi
storageClassName: standard
โ๏ธ Using PVC in Pod
spec:
containers:
- name: app
image: myapp:latest
volumeMounts:
- name: data
mountPath: /app/data
volumes:
- name: data
persistentVolumeClaim:
claimName: pvc-data
โ๏ธ Access Modes
- ReadWriteOnce (RWO) - Single node read-write
- ReadOnlyMany (ROX) - Multiple nodes read-only
- ReadWriteMany (RWX) - Multiple nodes read-write
Namespaces & Resource Quotas
๐น Command: kubectl create namespace
โ๏ธ What It Does
Creates namespaces for resource isolation and organization.
โ๏ธ Syntax Examples
# Basic: Create namespace
kubectl create namespace development
# Real-world: Create with labels
kubectl create namespace production --dry-run=client -o yaml | \
kubectl label -f - env=production --local -o yaml | \
kubectl apply -f -
# List namespaces
kubectl get namespaces
# Delete namespace (deletes all resources in it)
kubectl delete namespace development
โ๏ธ Notes, Tips & Common Mistakes
- Default namespaces:
default,kube-system,kube-public - Deleting namespace deletes all resources in it
- Use namespaces for environment separation (dev, staging, prod)
- Set default namespace:
kubectl config set-context --current --namespace=production
๐น Resource Quotas
โ๏ธ ResourceQuota Example
apiVersion: v1
kind: ResourceQuota
metadata:
name: compute-quota
namespace: development
spec:
hard:
requests.cpu: "10"
requests.memory: 20Gi
limits.cpu: "20"
limits.memory: 40Gi
persistentvolumeclaims: "10"
pods: "50"
โ๏ธ LimitRange Example
apiVersion: v1
kind: LimitRange
metadata:
name: resource-limits
namespace: development
spec:
limits:
- max:
cpu: "2"
memory: 4Gi
min:
cpu: 100m
memory: 128Mi
default:
cpu: 500m
memory: 512Mi
defaultRequest:
cpu: 250m
memory: 256Mi
type: Container
StatefulSets & DaemonSets
๐น StatefulSets
โ๏ธ What They Are
Manages stateful applications with stable network identities and persistent storage.
โ๏ธ StatefulSet Example
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
spec:
serviceName: postgres
replicas: 3
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:15
ports:
- containerPort: 5432
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 10Gi
โ๏ธ Key Features
- Stable pod names:
postgres-0,postgres-1,postgres-2 - Ordered deployment and scaling
- Persistent storage per pod
- Stable network identities
๐น DaemonSets
โ๏ธ What They Are
Ensures a pod runs on all (or selected) nodes. Used for node-level services.
โ๏ธ DaemonSet Example
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: node-exporter
spec:
selector:
matchLabels:
app: node-exporter
template:
metadata:
labels:
app: node-exporter
spec:
containers:
- name: node-exporter
image: prom/node-exporter:latest
ports:
- containerPort: 9100
hostNetwork: true
hostPID: true
โ๏ธ Common Use Cases
- Log collectors (Fluentd, Filebeat)
- Monitoring agents (Prometheus Node Exporter)
- Network plugins
- Storage daemons
Jobs & CronJobs
๐น Jobs
โ๏ธ What They Are
Runs pods to completion (batch processing, one-time tasks).
โ๏ธ Job Example
apiVersion: batch/v1
kind: Job
metadata:
name: data-migration
spec:
completions: 1
parallelism: 1
backoffLimit: 3
template:
spec:
containers:
- name: migrate
image: myapp:latest
command: ["python", "migrate.py"]
restartPolicy: Never
โ๏ธ Command Examples
# Create job
kubectl create job data-import --image=myapp:latest -- python import.py
# View job status
kubectl get jobs
# View job logs
kubectl logs job/data-migration
# Delete completed jobs
kubectl delete job data-migration
๐น CronJobs
โ๏ธ What They Are
Runs jobs on a schedule (like cron in Linux).
โ๏ธ CronJob Example
apiVersion: batch/v1
kind: CronJob
metadata:
name: backup-database
spec:
schedule: "0 2 * * *" # 2 AM daily
jobTemplate:
spec:
template:
spec:
containers:
- name: backup
image: postgres:15
command:
- /bin/sh
- -c
- pg_dump -h postgres -U admin mydb > /backup/db-$(date +%Y%m%d).sql
restartPolicy: OnFailure
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
โ๏ธ Cron Schedule Format
# โโโโโโโโโโโโโโ minute (0 - 59)
# โ โโโโโโโโโโโโโโ hour (0 - 23)
# โ โ โโโโโโโโโโโโโโ day of month (1 - 31)
# โ โ โ โโโโโโโโโโโโโโ month (1 - 12)
# โ โ โ โ โโโโโโโโโโโโโโ day of week (0 - 6) (Sunday to Saturday)
# โ โ โ โ โ
# * * * * *
Examples:
0 2 * * *- Daily at 2 AM*/15 * * * *- Every 15 minutes0 0 * * 0- Weekly on Sunday at midnight0 9-17 * * 1-5- Weekdays 9 AM to 5 PM
Ingress & Load Balancing
๐น Understanding Ingress
โ๏ธ What It Is
Manages external HTTP/HTTPS access to services. Provides load balancing, SSL termination, and name-based virtual hosting.
โ๏ธ Ingress Example
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: app-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
ingressClassName: nginx
tls:
- hosts:
- app.example.com
secretName: app-tls
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: frontend
port:
number: 80
- path: /api
pathType: Prefix
backend:
service:
name: backend
port:
number: 8080
โ๏ธ Common Ingress Controllers
- NGINX Ingress Controller (most popular)
- Traefik
- HAProxy
- AWS ALB Ingress Controller
- GCE Ingress Controller
RBAC & Security
๐น Role-Based Access Control
โ๏ธ Role Example (Namespace-scoped)
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: pod-reader
namespace: development
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
โ๏ธ ClusterRole Example (Cluster-wide)
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: cluster-admin-custom
rules:
- apiGroups: ["*"]
resources: ["*"]
verbs: ["*"]
โ๏ธ RoleBinding Example
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: development
subjects:
- kind: User
name: john
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
โ๏ธ Common Verbs
get,list,watch- Read operationscreate,update,patch- Write operationsdelete,deletecollection- Delete operations*- All operations
๐น Security Best Practices
โ๏ธ Pod Security Standards
apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 2000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: myapp:latest
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
โ๏ธ Network Policies
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-network-policy
spec:
podSelector:
matchLabels:
app: api
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
egress:
- to:
- podSelector:
matchLabels:
app: database
ports:
- protocol: TCP
port: 5432
Helm Package Manager
๐น Command: helm install
โ๏ธ What It Does
Installs Helm charts (packaged Kubernetes applications).
โ๏ธ Syntax Examples
# Basic: Install chart
helm install my-release stable/nginx
# Real-world: Install with custom values
helm install my-app ./my-chart -f values.yaml
# Production: Install with overrides
helm install my-app ./my-chart \
--set image.tag=v2.0.0 \
--set replicas=3 \
--namespace production \
--create-namespace
# Dry run
helm install my-app ./my-chart --dry-run --debug
๐น Command: helm upgrade
โ๏ธ What It Does
Upgrades an existing release.
โ๏ธ Syntax Examples
# Basic: Upgrade release
helm upgrade my-app ./my-chart
# Real-world: Upgrade with new values
helm upgrade my-app ./my-chart -f new-values.yaml
# Production: Upgrade or install
helm upgrade --install my-app ./my-chart
# Rollback on failure
helm upgrade my-app ./my-chart --atomic --timeout 5m
๐น Other Helm Commands
# List releases
helm list
# Show release history
helm history my-app
# Rollback to previous version
helm rollback my-app
# Rollback to specific revision
helm rollback my-app 3
# Uninstall release
helm uninstall my-app
# Add repository
helm repo add bitnami https://charts.bitnami.com/bitnami
# Update repositories
helm repo update
# Search for charts
helm search repo nginx
Troubleshooting & Debugging
๐น Common Debugging Commands
# Check pod status and events
kubectl describe pod <pod-name>
# View pod logs
kubectl logs <pod-name>
kubectl logs <pod-name> --previous # Previous container instance
# Check resource usage
kubectl top nodes
kubectl top pods
# Get events
kubectl get events --sort-by=.metadata.creationTimestamp
# Check service endpoints
kubectl get endpoints <service-name>
# Test DNS resolution
kubectl run -it --rm debug --image=busybox --restart=Never -- nslookup kubernetes.default
# Test network connectivity
kubectl run -it --rm debug --image=nicolaka/netshoot --restart=Never -- bash
# Check API server
kubectl get --raw /healthz
# View cluster info
kubectl cluster-info dump
๐น Common Issues & Solutions
Pod Stuck in Pending
# Check events
kubectl describe pod <pod-name>
# Common causes:
# - Insufficient resources
# - PVC not bound
# - Node selector mismatch
# - Taints/tolerations
# Check node resources
kubectl describe nodes
Pod CrashLoopBackOff
# Check logs
kubectl logs <pod-name> --previous
# Common causes:
# - Application error
# - Missing dependencies
# - Incorrect command/args
# - Failed health checks
ImagePullBackOff
# Check events
kubectl describe pod <pod-name>
# Common causes:
# - Image doesn't exist
# - Registry authentication failed
# - Network issues
# - Typo in image name
Service Not Accessible
# Check endpoints
kubectl get endpoints <service-name>
# Check selectors match
kubectl get pods --show-labels
kubectl describe service <service-name>
# Test from within cluster
kubectl run -it --rm debug --image=busybox --restart=Never -- wget -O- <service-name>
Production Best Practices
โ Resource Management
- Always set resource requests and limits
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 512Mi
- Use Horizontal Pod Autoscaler
kubectl autoscale deployment nginx --min=2 --max=10 --cpu-percent=80
- Implement Pod Disruption Budgets
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: app-pdb
spec:
minAvailable: 2
selector:
matchLabels:
app: myapp
โ Health Checks
Always define liveness and readiness probes:
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
โ Deployment Strategy
Use rolling updates with proper configuration:
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
minReadySeconds: 10
โ Security Checklist
- Run containers as non-root
- Use read-only root filesystem
- Drop all capabilities, add only needed ones
- Implement Network Policies
- Use RBAC with least privilege
- Scan images for vulnerabilities
- Use Pod Security Standards
- Encrypt secrets at rest
- Enable audit logging
- Regularly update Kubernetes version
โ Monitoring & Logging
Essential monitoring stack:
- Prometheus - Metrics collection
- Grafana - Visualization
- ELK/EFK Stack - Log aggregation
- Jaeger/Zipkin - Distributed tracing
Key metrics to monitor:
- Pod CPU/Memory usage
- Node resources
- API server latency
- etcd performance
- Network traffic
- Application-specific metrics
โ Backup & Disaster Recovery
# Backup etcd
ETCDCTL_API=3 etcdctl snapshot save backup.db
# Backup all resources
kubectl get all --all-namespaces -o yaml > cluster-backup.yaml
# Use Velero for production backups
velero backup create full-backup --include-namespaces=production
Quick Reference Card
Most Used Commands
# Context & Config
kubectl config get-contexts
kubectl config use-context <context>
kubectl config set-context --current --namespace=<namespace>
# Resources
kubectl get pods -A
kubectl get all
kubectl describe pod <name>
kubectl logs -f <pod>
kubectl exec -it <pod> -- /bin/bash
# Apply & Delete
kubectl apply -f manifest.yaml
kubectl delete -f manifest.yaml
kubectl delete pod <name> --force --grace-period=0
# Deployments
kubectl create deployment <name> --image=<image>
kubectl scale deployment <name> --replicas=3
kubectl set image deployment/<name> <container>=<image>
kubectl rollout status deployment/<name>
kubectl rollout undo deployment/<name>
# Services
kubectl expose deployment <name> --port=80
kubectl get svc
kubectl port-forward svc/<name> 8080:80
# Debugging
kubectl describe pod <name>
kubectl logs <pod> --previous
kubectl top nodes
kubectl top pods
kubectl get events --sort-by=.metadata.creationTimestamp
๐ Kubernetes Master Class Complete
This comprehensive guide covers everything from basic kubectl commands to production-ready Kubernetes deployments. Master these concepts to orchestrate containers at scale with confidence.