/user/kayd @ devops :~$ cat kubernetes.md

Kubernetes Cheatsheet Kubernetes Cheatsheet

QR Code linking to: Kubernetes Cheatsheet
Karandeep Singh
Karandeep Singh
• 6 minutes

Summary

A working kubectl reference with core resource YAML skeletons, rollout and scaling commands, debugging workflows, and a table of handy one-liners.

I spend a good chunk of every week inside kubectl and still blank on flag combinations at the worst moments, so this page is my working memory. Commands, YAML skeletons, and the debugging moves I actually use on real clusters. Everything here assumes your images are already built and pushed; my Docker Cheatsheet covers that half of the workflow.

kubectl Basics

Docs: kubectl reference on kubernetes.io

kubectl get pods                          # Pods in current namespace
kubectl get pods -n kube-system           # Specific namespace
kubectl get pods -A                       # All namespaces
kubectl get pods -o wide                  # Node, IP, readiness detail
kubectl get deploy web -o yaml            # Full live manifest
kubectl describe pod web-7d4b9c6f5-x2k8j  # Events, conditions, mounts
kubectl logs web-7d4b9c6f5-x2k8j          # Container logs
kubectl logs -f deploy/web                # Follow logs via the Deployment
kubectl logs web-... -c sidecar --previous   # Prior crashed container
kubectl exec -it web-... -- sh            # Shell into a pod
kubectl apply -f manifest.yaml            # Create/update declaratively
kubectl apply -f k8s/ -R                  # Whole directory, recursive
kubectl delete -f manifest.yaml
kubectl delete pod web-... --grace-period=0 --force   # Last resort
kubectl diff -f manifest.yaml             # Preview what apply would change
FlagMeaning
-n <ns>Target a namespace
-AAll namespaces
-o wideExtra columns (node, IP)
-o yaml / -o jsonFull object output
-o jsonpath='{...}'Extract specific fields
-l app=webFilter by label selector
--watch / -wStream changes live
--dry-run=client -o yamlGenerate YAML without creating

Context & Namespace Switching

Docs: Kubernetes docs on configuring access to multiple clusters

kubectl config get-contexts               # List clusters/contexts
kubectl config current-context
kubectl config use-context prod-cluster
kubectl config set-context --current --namespace=payments   # Default ns

I alias these constantly. kubectx and kubens do the same job with less typing if you can install them.

Core Resource YAML Skeletons

Docs: Kubernetes Deployment docs

Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  labels:
    app: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: registry.example.com/team/web:1.4.2
          ports:
            - containerPort: 8080
          envFrom:
            - configMapRef:
                name: web-config
            - secretRef:
                name: web-secrets
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              memory: 256Mi
          readinessProbe:
            httpGet:
              path: /healthz
              port: 8080
            initialDelaySeconds: 5
            periodSeconds: 10

Service

apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  type: ClusterIP        # NodePort / LoadBalancer for external
  selector:
    app: web
  ports:
    - port: 80
      targetPort: 8080

ConfigMap & Secret

apiVersion: v1
kind: ConfigMap
metadata:
  name: web-config
data:
  LOG_LEVEL: info
  FEATURE_FLAGS: "beta-ui,new-checkout"
---
apiVersion: v1
kind: Secret
metadata:
  name: web-secrets
type: Opaque
stringData:            # stringData = plain text; k8s base64-encodes it
  DATABASE_URL: postgres://app:secret@db:5432/app
kubectl create secret generic web-secrets \
  --from-literal=DATABASE_URL=postgres://... --dry-run=client -o yaml

Ingress

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  ingressClassName: nginx
  tls:
    - hosts: [app.example.com]
      secretName: web-tls
  rules:
    - host: app.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web
                port:
                  number: 80

Rollouts

Docs: Kubernetes docs on updating and rolling back Deployments

kubectl rollout status deploy/web         # Block until rollout completes
kubectl rollout history deploy/web        # Revision list
kubectl rollout history deploy/web --revision=3   # Details of one revision
kubectl rollout undo deploy/web           # Roll back to previous
kubectl rollout undo deploy/web --to-revision=2
kubectl rollout restart deploy/web        # Rolling restart (picks up config changes)
kubectl set image deploy/web web=registry.example.com/team/web:1.4.3

Scaling & Autoscaling

Docs: Horizontal Pod Autoscaling on kubernetes.io

kubectl scale deploy/web --replicas=5
kubectl autoscale deploy/web --min=3 --max=10 --cpu-percent=70
kubectl get hpa
kubectl top pods                          # Needs metrics-server
kubectl top nodes

kubectl autoscale generates an autoscaling/v2 HorizontalPodAutoscaler behind the scenes. Export it with kubectl get hpa web -o yaml if you want to commit it declaratively (that is where memory and custom-metric targets go too).

Port-Forward

Docs: Kubernetes port-forwarding docs

kubectl port-forward svc/web 8080:80              # localhost:8080 → service:80
kubectl port-forward deploy/web 8080:8080
kubectl port-forward pod/db-0 5432:5432 -n data   # Handy for DB clients

Debugging

Docs: Monitoring, logging, and debugging on kubernetes.io

kubectl get events --sort-by=.lastTimestamp       # Recent cluster events
kubectl get events --field-selector involvedObject.name=web-7d4b9c6f5-x2k8j
kubectl describe pod web-...                      # Events section at the bottom
kubectl debug -it web-... --image=busybox --target=web   # Ephemeral container
kubectl debug node/worker-3 -it --image=ubuntu    # Debug pod on a node
kubectl get pod web-... -o jsonpath='{.status.containerStatuses[0].lastState}'

CrashLoopBackOff Triage

  1. kubectl logs web-... --previous. The crash reason is almost always here.
  2. kubectl describe pod web-..., then check Events for OOMKilled, failed probes, image pull errors.
  3. Exit code 137 → OOMKilled: raise memory limits or fix the leak.
  4. Failing liveness probe → the app is slow to start; raise initialDelaySeconds or switch to a startup probe.
  5. Still stuck? Override the entrypoint to keep the pod alive and poke around: kubectl debug with an ephemeral container, or set command: ["sleep", "3600"] in a copy of the pod.

Labels & Selectors

Docs: Kubernetes labels and selectors docs

kubectl get pods -l app=web                       # Equality selector
kubectl get pods -l 'env in (staging,prod)'       # Set-based selector
kubectl get pods -l app=web,tier!=cache
kubectl label pod web-... debug=true              # Add a label
kubectl label pod web-... debug-                  # Remove it
kubectl get pods --show-labels

Services, Deployments, HPAs, and NetworkPolicies all match pods by labels. A Service with selector: app: web routes to every ready pod carrying that label, no matter what created it.

Resource Requests & Limits

Docs: Kubernetes docs on resource management for Pods and containers

SettingEffect
requests.cpu / requests.memoryWhat the scheduler reserves; pod won’t schedule without capacity
limits.cpuThrottled above this (no kill)
limits.memoryOOM-killed above this (exit 137)

My defaults: always set requests (scheduling accuracy), set a memory limit (protect neighbours), and think twice before CPU limits, because throttling shows up as mystery latency.

Handy One-Liners

Docs: kubectl quick reference on kubernetes.io

TaskCommand
Generate Deployment YAMLkubectl create deploy web --image=nginx --dry-run=client -o yaml
Throwaway debug podkubectl run tmp --rm -it --image=busybox -- sh
Decode a secretkubectl get secret web-secrets -o jsonpath='{.data.DATABASE_URL}' | base64 -d
Pods on one nodekubectl get pods -A --field-selector spec.nodeName=worker-3
Restart countskubectl get pods -o custom-columns=NAME:.metadata.name,RESTARTS:.status.containerStatuses[0].restartCount
All images running in clusterkubectl get pods -A -o jsonpath='{range .items[*]}{.spec.containers[*].image}{"\n"}{end}' | sort -u
Drain a nodekubectl drain worker-3 --ignore-daemonsets --delete-emptydir-data
Uncordon it afterkubectl uncordon worker-3
Delete all Evicted podskubectl delete pods -A --field-selector status.phase=Failed
Watch a rollout livekubectl get pods -l app=web -w

Most of my controllers and operators are written in Go. The client-go ecosystem is a big reason I keep my Go (Golang) Cheatsheet nearby when working against the Kubernetes API.

  • Docker: multi-stage builds, image tagging, volumes, and compose. Every Pod spec on this page starts there
  • Go (Golang): the language kubectl and most operators are written in. Toolchain, goroutines, channels, and table-driven tests
  • AWS CloudFormation: templates, change sets, and drift detection for the VPCs and cluster infrastructure underneath these workloads

More container pages sit in the Containers group; the full index is the cheatsheet library.

Similar Articles

More from devops

tmux Cheatsheet

Quick-reference tmux cheatsheet: sessions, windows, panes, copy mode, synchronize-panes, .tmux.conf …

Jenkins Cheatsheet

Jenkins cheatsheet with declarative pipeline syntax, credentials, parameters, parallel stages, …

Docker Cheatsheet

Docker cheatsheet with the commands I use daily as a DevOps engineer: image builds, run flags, …

No related topic suggestions found.