Kubernetes
kubectl commands, Pod/Deployment/Service manifests, config management, and cluster operations.
Kubernetes Basics
2 topics
Core Concepts: Cluster, Node, Pod, Namespace
Kubernetes runs containerized apps on a cluster. A cluster has a control plane and worker nodes. Pods are the smallest deployable unit and usually contain one container. Namespaces logically separate resources.
# Check cluster info
kubectl cluster-info
# List nodes
kubectl get nodes -o wide
# List all namespaces
kubectl get namespaces
# List pods in default namespace
kubectl get pods
# List pods in all namespaces
kubectl get pods -AThink of Pods as temporary app instances; Deployments manage Pod lifecycle.
Use namespaces to isolate environments like dev, staging, and prod.
kubectl Context and Namespace Management
kubectl uses kubeconfig contexts to switch between clusters/users. Set a default namespace per context to avoid repeating -n.
# Show current context
kubectl config current-context
# List contexts
kubectl config get-contexts
# Switch context
kubectl config use-context my-cluster-context
# Set default namespace for current context
kubectl config set-context --current --namespace=dev
# Verify namespace setting
kubectl config view --minify | grep namespace:Always verify your context before applying changes.
Set namespace once per context to reduce mistakes.
kubectl Basics
1 topic
Essential Commands
# Context / namespace
kubectl config get-contexts
kubectl config use-context my-cluster
kubectl config set-context --current --namespace=my-ns
# Get resources
kubectl get pods
kubectl get pods -n kube-system
kubectl get all
kubectl describe pod my-pod
# Logs & exec
kubectl logs my-pod
kubectl logs -f my-pod --tail=100 # Follow
kubectl logs my-pod -c my-container # Specific container
kubectl exec -it my-pod -- /bin/sh
# Port forward
kubectl port-forward pod/my-pod 8080:8080
kubectl port-forward svc/my-svc 3000:80💡 Set a default namespace with config set-context to avoid -n on every command
⚡ port-forward is great for debugging services without exposing them
Manifests
2 topics
Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
labels:
app: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: my-app:1.2.3
ports:
- containerPort: 8080
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 512Mi
readinessProbe:
httpGet:
path: /health
port: 8080⚠️ Always set resource requests/limits — unbounded pods can starve the node
💡 readinessProbe prevents traffic from reaching pods that aren't ready
Service & ConfigMap
# Service
apiVersion: v1
kind: Service
metadata:
name: my-app
spec:
selector:
app: my-app
ports:
- port: 80
targetPort: 8080
type: ClusterIP
---
# ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
LOG_LEVEL: info
API_URL: https://api.example.com
---
# Secret
apiVersion: v1
kind: Secret
metadata:
name: app-secrets
type: Opaque
stringData:
DATABASE_URL: postgresql://user:pass@db:5432/app⚠️ Secrets are base64-encoded, NOT encrypted by default — use a secrets manager in production
Workloads and Scaling
3 topics
Deployments: Create, Update, and Roll Back
Deployments manage stateless app Pods and provide rollout/rollback features.
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
labels:
app: web-app
spec:
replicas: 2
selector:
matchLabels:
app: web-app
template:
metadata:
labels:
app: web-app
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80Keep labels consistent between selector.matchLabels and template.metadata.labels.
Use explicit image tags; avoid latest in production.
Common Deployment Commands
Use kubectl to apply manifests, inspect rollout state, scale replicas, and revert bad releases.
# Apply deployment
kubectl apply -f deployment.yaml
# Check deployment and pods
kubectl get deploy,pods -l app=web-app
# Watch rollout status
kubectl rollout status deployment/web-app
# Update image
kubectl set image deployment/web-app nginx=nginx:1.26
# View rollout history
kubectl rollout history deployment/web-app
# Roll back to previous revision
kubectl rollout undo deployment/web-app
# Scale replicas
kubectl scale deployment/web-app --replicas=4Use rollout status after each update to catch failures quickly.
Scaling affects replica count, not container resources.
Jobs and CronJobs for Batch Work
Jobs run tasks to completion once; CronJobs run Jobs on a schedule.
apiVersion: batch/v1
kind: CronJob
metadata:
name: nightly-report
spec:
schedule: "0 2 * * *"
jobTemplate:
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: report
image: busybox:1.36
command: ["/bin/sh", "-c", "echo generating report; sleep 5"]Set restartPolicy to OnFailure or Never for Job/CronJob pods.
Use CronJobs for periodic tasks like backups or reports.
Scaling & Updates
2 topics
Scale & Rolling Updates
# Scale replicas
kubectl scale deployment my-app --replicas=5
# Trigger rolling update (new image)
kubectl set image deployment/my-app my-app=my-app:2.0.0
# Monitor rollout
kubectl rollout status deployment/my-app
kubectl rollout history deployment/my-app
# Rollback to previous version
kubectl rollout undo deployment/my-app
kubectl rollout undo deployment/my-app --to-revision=2⚡ Rolling updates replace pods incrementally — zero downtime by default
💡 rollout undo is the fastest recovery from a bad deploy — keep revision history
Horizontal Pod Autoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70⚠️ HPA requires resource requests on containers — it silently does nothing without them
💡 Start with CPU-based HPA; add custom metrics once traffic patterns are understood
Networking and Service Discovery
3 topics
Services: ClusterIP, NodePort, LoadBalancer
Services provide stable networking for Pods. ClusterIP is internal-only, NodePort exposes on node ports, LoadBalancer integrates with cloud load balancers.
apiVersion: v1
kind: Service
metadata:
name: web-service
spec:
selector:
app: web-app
ports:
- port: 80
targetPort: 80
type: ClusterIPService selectors must match Pod labels.
Use ClusterIP by default; expose externally only when needed.
Ingress for HTTP Routing
Ingress routes HTTP(S) traffic to Services by host/path. Requires an Ingress controller (e.g., NGINX Ingress).
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-ingress
spec:
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web-service
port:
number: 80Ingress alone is not enough; an Ingress controller must be installed.
Start with one host/path rule, then add complexity.
Port Forwarding and DNS Checks
Port-forwarding helps local debugging without public exposure. DNS service names let Pods discover Services.
# Forward local port 8080 to service port 80
kubectl port-forward service/web-service 8080:80
# Open http://localhost:8080
# Run a temporary pod to test DNS resolution
kubectl run dns-test --image=busybox:1.36 --restart=Never -it --rm -- nslookup web-service.default.svc.cluster.localPort-forward is great for quick testing in dev.
Service DNS format: <service>.<namespace>.svc.cluster.local.
Ingress & Services
2 topics
Service Types
# ClusterIP — internal only (default)
spec:
type: ClusterIP # reachable only inside cluster
# NodePort — exposes a port on every node
spec:
type: NodePort
ports:
- port: 80
nodePort: 30080 # valid range: 30000-32767
# LoadBalancer — cloud provider creates external LB
spec:
type: LoadBalancer
# Check assigned external IP
kubectl get svc my-app⚠️ NodePort is for debugging only — use Ingress for production HTTP traffic
💡 LoadBalancer creates one cloud LB per service; use Ingress to share a single LB
Ingress Resource
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-app-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
ingressClassName: nginx
rules:
- host: api.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-app
port:
number: 80
tls:
- hosts:
- api.example.com
secretName: api-tls💡 Ingress needs a controller (nginx, traefik) deployed in the cluster to work
⚡ TLS at the Ingress keeps backend services simple — no cert handling per service
Configuration and Storage
3 topics
ConfigMaps and Secrets
ConfigMaps store non-sensitive config. Secrets store sensitive values (base64-encoded, optionally encrypted at rest).
# Create ConfigMap from literals
kubectl create configmap app-config --from-literal=APP_ENV=dev --from-literal=LOG_LEVEL=info
# Create Secret from literals
kubectl create secret generic db-secret --from-literal=DB_USER=app --from-literal=DB_PASS='s3cr3t'
# Inspect resources
kubectl get configmap app-config -o yaml
kubectl get secret db-secret -o yamlDo not commit real secrets to git in plain YAML.
Mount config as env vars or files depending on app needs.
Use ConfigMap/Secret in a Pod
Inject configuration into containers through environment variables.
apiVersion: v1
kind: Pod
metadata:
name: config-demo
spec:
containers:
- name: app
image: busybox:1.36
command: ["/bin/sh", "-c", "env | grep -E 'APP_ENV|DB_USER'; sleep 3600"]
env:
- name: APP_ENV
valueFrom:
configMapKeyRef:
name: app-config
key: APP_ENV
- name: DB_USER
valueFrom:
secretKeyRef:
name: db-secret
key: DB_USERValidate key names in ConfigMap/Secret before referencing.
Prefer Deployments over standalone Pods for real apps.
Persistent Volumes (PV), Claims (PVC), and Mounting
Use PVCs to request storage without hardcoding infrastructure details in workloads.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: app-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-with-storage
spec:
replicas: 1
selector:
matchLabels:
app: web-storage
template:
metadata:
labels:
app: web-storage
spec:
containers:
- name: app
image: nginx:1.25
volumeMounts:
- name: data
mountPath: /usr/share/nginx/html
volumes:
- name: data
persistentVolumeClaim:
claimName: app-pvcPVC status must be Bound before app can mount storage.
StorageClass often auto-provisions underlying volumes.
Troubleshooting
2 topics
Debug Commands
# Pod not starting — check Events first
kubectl describe pod my-pod
kubectl get events --sort-by=.metadata.creationTimestamp
# CrashLoopBackOff — view last container logs
kubectl logs my-pod --previous
# Run a debug pod in the cluster
kubectl run debug --image=busybox -it --rm -- sh
# Copy files from a pod
kubectl cp my-pod:/app/logs ./logs
# Resource usage
kubectl top pods
kubectl top nodes💡 describe Events is where the real error message usually appears
⚡ --previous shows logs from the crashed container before it restarted
Common Pod Issues
# ImagePullBackOff — wrong image or missing registry credentials
kubectl describe pod my-pod | grep -A10 Events
# Pending — not enough resources or no matching node
kubectl describe pod my-pod | grep 'Insufficient\|Unschedulable'
# OOMKilled — memory limit too low
kubectl describe pod my-pod | grep -i 'oom\|killed'
# Check node health and pressure
kubectl describe node my-node | grep -A5 Conditions
# Force-delete a stuck terminating pod
kubectl delete pod my-pod --grace-period=0 --force⚠️ --force delete skips graceful shutdown — only use on pods stuck in Terminating
💡 OOMKilled always means: raise the memory limit or fix a memory leak — never ignore it
Troubleshooting and Daily Commands
3 topics
Inspect Resource State Quickly
Start with get and describe to check status, events, and scheduling issues.
# List common resources
kubectl get pods,deploy,svc
# Wide output with node/IP details
kubectl get pods -o wide
# Describe pod for events and failures
kubectl describe pod <pod-name>
# Get recent events
kubectl get events --sort-by=.metadata.creationTimestampdescribe often reveals image pull, probe, and scheduling errors.
Events are time-sensitive; check them early.
Logs and Exec Into Containers
Use logs for runtime errors and exec for in-container debugging.
# Pod logs
kubectl logs <pod-name>
# Follow logs
kubectl logs -f <pod-name>
# Logs from previous crashed container
kubectl logs <pod-name> --previous
# Exec into container shell
kubectl exec -it <pod-name> -- /bin/shUse --previous when containers restart (CrashLoopBackOff).
If multiple containers exist, add -c <container-name>.
Imperative Shortcuts and Safe Cleanup
Imperative commands are useful for quick tasks; use labels/selectors and dry-run for safer operations.
# Run temporary pod
kubectl run tmp --image=busybox:1.36 --restart=Never -- sleep 3600
# Create deployment quickly
kubectl create deployment hello --image=nginx:1.25
# Expose deployment as service
kubectl expose deployment hello --port=80 --target-port=80 --type=ClusterIP
# Preview YAML without applying
kubectl create deployment demo --image=nginx:1.25 --dry-run=client -o yaml
# Delete by label
kubectl delete pod -l app=web-appPrefer declarative YAML for repeatable production workflows.
Use labels consistently to simplify bulk operations.
Related Cheat Sheets
More hands-on references connected to this topic.
Container management, Dockerfile syntax, docker-compose, networking, and volume management.
shared topics
Google Cloud Platform essentials: Compute Engine, GKE, Cloud Run, Cloud Storage, IAM, and core CLI commands.
shared topics
shared topics
LangGraph stateful agents, graph nodes, edges, checkpointing, and multi-agent workflows.
same difficulty, keyword overlap
Related Articles
Background reading and deeper explanations for this sheet.
GenAI SaaS Architecture: A Practical Blueprint for Building, Scaling, and Securing AI Products
Designing a SaaS product on top of GenAI is more than calling an LLM API—it requires thoughtful architecture across product, data, safety, and operations. This practical guide walks you through a beginner-friendly yet deep system blueprint, with real-world patterns, code snippets, and deployment strategies you can use immediately.
keyword overlap
Scaling AI APIs with FastAPI, Docker, and Load Balancers: A Practical Guide for Production
Building an AI API is easy—keeping it fast and reliable under real traffic is the hard part. In this practical guide, you’ll learn how to scale FastAPI services with Docker and load balancers, from local setup to production architecture, with real-world examples, code, and deployment tips.
keyword overlap
Building Autonomous Agents Without Overengineering: A Practical Guide for Real-World Teams
Autonomous agents can automate meaningful work, but many projects fail because teams overbuild too early. This practical guide shows you how to design, ship, and improve useful agents with simple patterns, clear guardrails, and real-world examples—without turning your stack into a science project.
keyword overlap
Cost Optimization in Agentic Systems: The Most Underrated Lever for Reliable AI at Scale
Most teams building agentic systems obsess over accuracy and latency, but ignore the fastest path to sustainable scale: cost optimization. In this guide, you’ll learn practical cost models, real architecture patterns, and implementation tactics to cut spend without sacrificing quality or autonomy.
keyword overlap