Containers21 min read1,705 lines

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

  1. Core Concepts
  2. kubectl Basics
  3. Pod Management
  4. Deployments & ReplicaSets
  5. Services & Networking
  6. ConfigMaps & Secrets
  7. Volumes & Storage
  8. Namespaces & Resource Quotas
  9. StatefulSets & DaemonSets
  10. Jobs & CronJobs
  11. Ingress & Load Balancing
  12. RBAC & Security
  13. Helm Package Manager
  14. Troubleshooting & Debugging
  15. 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 kubectx and kubens tools 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 wide shows more details (node, IP)
  • -A or --all-namespaces searches entire cluster
  • -w watches for real-time changes
  • -l filters by labels (key=value)
  • Use -o yaml to 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 apply over create (idempotent, can update)
  • --dry-run=client validates locally
  • --dry-run=server validates against API server
  • Use -f - to read from stdin
  • --record saves 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
  • --force should be last resort (can cause issues)
  • Deleting deployment also deletes pods
  • Use labels for bulk operations carefully
  • --all is 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

  • --rm deletes pod after exit (useful for testing)
  • -it for interactive terminal
  • Use --dry-run=client -o yaml to 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

  • -f follows logs (like tail -f)
  • --previous shows logs from crashed container
  • -c required 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

  • -it required for interactive sessions
  • Use /bin/sh if /bin/bash not available
  • -- separates kubectl args from command args
  • -c specifies 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 tar in container
  • Not suitable for large files
  • Use volumes for persistent data
  • -c specifies 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-replicas provides 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

  • restart is useful for picking up ConfigMap changes
  • pause allows testing before full rollout
  • Use --record with 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 status to 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

  • --port is service port, --target-port is 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 minutes
  • 0 0 * * 0 - Weekly on Sunday at midnight
  • 0 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 operations
  • create, update, patch - Write operations
  • delete, 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

  1. Always set resource requests and limits
resources:
  requests:
    cpu: 100m
    memory: 128Mi
  limits:
    cpu: 500m
    memory: 512Mi
  1. Use Horizontal Pod Autoscaler
kubectl autoscale deployment nginx --min=2 --max=10 --cpu-percent=80
  1. 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.