On this page

Kubernetes Cheat Sheet

Quick reference for kubectl commands, Kubernetes resource types, debugging, and common YAML patterns.

Deep dive: Kubernetes Section | K8s Production Checklist | Power user: kubectl Advanced


kubectl Basics

Context & Config

CommandDescription
kubectl config get-contextsList all contexts
kubectl config current-contextShow current context
kubectl config use-context ctxSwitch context
kubectl config set-context --current --namespace=nsSet default namespace
kubectl cluster-infoCluster endpoint info
kubectl api-resourcesList all resource types
kubectl api-versionsList API versions
kubectl versionClient and server versions (keep kubectl within one minor of the server)
kubectl explain pod.spec.containersBuilt-in field docs for any resource
kubectl auth whoamiShow the identity the API server sees

Get Resources

CommandDescription
kubectl get podsList pods in current namespace
kubectl get pods -AList pods in all namespaces
kubectl get pods -o widePods with node and IP info
kubectl get pods -o yamlFull YAML output
kubectl get pods -l app=webFilter by label
kubectl get pods --field-selector status.phase=RunningFilter by field
kubectl get pods --sort-by=.metadata.creationTimestampSort by creation time
kubectl get allCommon workload resources in namespace (not ConfigMaps, Secrets, Ingresses, PVCs)
kubectl get events --sort-by=.lastTimestampEvents sorted by time (lastTimestamp can be empty for newer events)
kubectl eventsEvents sorted by time (GA since 1.28; preferred)
kubectl events --for pod/pod-nameEvents for one object
kubectl get pods -wWatch for changes

Create & Apply

CommandDescription
kubectl apply -f manifest.yamlCreate or update from file
kubectl apply -f ./dir/Apply all files in directory
kubectl apply -k ./kustomize/Apply with Kustomize
kubectl create ns my-namespaceCreate namespace
kubectl create secret generic s --from-literal=k=vCreate secret from literal
kubectl create secret generic s --from-file=./key.pemCreate secret from file
kubectl create configmap cm --from-literal=k=vCreate configmap
kubectl create secret tls app-tls --cert=tls.crt --key=tls.keyCreate TLS secret
kubectl create secret docker-registry regcred --docker-server=ghcr.io --docker-username=u --docker-password=TOKENImage pull secret
kubectl diff -f manifest.yamlShow what apply would change
kubectl apply --server-side -f manifest.yamlServer-side apply (field ownership tracked by the API server)
kubectl create deploy web --image=nginx:1.27 --dry-run=client -o yamlGenerate a YAML skeleton

Edit & Delete

CommandDescription
kubectl edit deployment appEdit resource in editor
kubectl delete -f manifest.yamlDelete from file
kubectl delete pod pod-nameDelete specific pod
kubectl delete pods -l app=webDelete pods by label
kubectl delete ns my-namespaceDelete namespace and everything in it
kubectl delete -f manifest.yaml -iInteractive delete: list and confirm first
kubectl label pod pod-name env=prod --overwriteAdd or change a label

Describe & Logs

CommandDescription
kubectl describe pod pod-nameDetailed pod info with events
kubectl describe node node-nameNode capacity and allocations
kubectl logs pod-namePod logs
kubectl logs pod-name -c containerSpecific container logs
kubectl logs pod-name --previousPrevious container logs (after crash)
kubectl logs -f pod-nameFollow logs
kubectl logs -l app=web --all-containersLogs from all pods with label (last 10 lines each, max 5 pods)
kubectl logs deploy/app --since=1h --tail=200Logs from one pod of a deployment, time/line limited

Exec & Port-Forward

CommandDescription
kubectl exec -it pod-name -- shShell into pod
kubectl exec pod-name -- cmdRun command in pod
kubectl port-forward pod-name 8080:3000Forward local port to pod
kubectl port-forward svc/service 8080:80Forward local port to service
kubectl cp pod-name:/path ./localCopy from pod (needs tar in the container)
kubectl debug -it pod-name --image=busybox --target=appEphemeral debug container (for distroless images)

Scaling & Rollouts

CommandDescription
kubectl scale deployment app --replicas=5Scale deployment
kubectl autoscale deployment app --min=2 --max=10 --cpu=80%Create HPA (--cpu replaces the older --cpu-percent)
kubectl rollout status deployment appWatch rollout progress
kubectl rollout history deployment appRollout history
kubectl rollout undo deployment appRollback to previous
kubectl rollout undo deployment app --to-revision=2Rollback to specific revision
kubectl rollout restart deployment appRolling restart
kubectl rollout pause deployment app / resumeBatch several changes into one rollout
kubectl set image deployment app app=app:1.1.0Update image (starts a rollout)
kubectl drain node --ignore-daemonsets --delete-emptydir-dataEvict pods before node maintenance
kubectl cordon node / uncordon nodeStop / resume scheduling on a node

Resource Types Quick Reference

ResourceShortPurpose
PodpoSmallest deployable unit
DeploymentdeployDeclarative pod management with rollouts
StatefulSetstsStateful workloads with stable identity
DaemonSetdsOne pod per node
JobjobRun to completion
CronJobcjScheduled jobs
ServicesvcNetwork endpoint for pods
IngressingHTTP routing and TLS termination
ConfigMapcmNon-sensitive configuration
SecretsecretSensitive configuration
PersistentVolumeClaimpvcStorage request
NamespacensResource isolation
ServiceAccountsaPod identity
RoleroleNamespace-scoped permissions
ClusterRoleclusterroleCluster-scoped permissions
NetworkPolicynetpolNetwork traffic rules
HorizontalPodAutoscalerhpaAuto-scale by metrics
ReplicaSetrsKeeps N pod replicas (managed by Deployments)
PersistentVolumepvCluster-wide storage volume
StorageClassscDynamic volume provisioning profile
PodDisruptionBudgetpdbLimit voluntary evictions (drains, upgrades)
EndpointSlice(none)Pod IPs behind a Service (replaces deprecated Endpoints)
Gateway / HTTPRoutegtw / (none)Gateway API: successor to Ingress for L4/L7 routing
CustomResourceDefinitioncrdExtends the API with new types
NodenoWorker machine

Removed or deprecated APIs you may still see in old YAML

  • extensions/v1beta1 and apps/v1beta1/v1beta2 for Deployments, DaemonSets, ReplicaSets: removed in 1.16. Use apps/v1.
  • extensions/v1beta1 / networking.k8s.io/v1beta1 Ingress: removed in 1.22. Use networking.k8s.io/v1.
  • batch/v1beta1 CronJob: removed in 1.25. Use batch/v1.
  • autoscaling/v2beta1/v2beta2 HPA: removed in 1.25/1.26. Use autoscaling/v2.
  • PodSecurityPolicy (policy/v1beta1): removed in 1.25. Use Pod Security Admission namespace labels (below) or a policy engine (Kyverno, OPA Gatekeeper, ValidatingAdmissionPolicy).
  • dockershim: removed in 1.24. Nodes run containerd or CRI-O; Docker-built images still work.
  • v1 Endpoints: deprecated in 1.33. Use EndpointSlices.

Find them with kubectl convert (plugin) or a scanner such as pluto / kubent.


Common YAML Templates

Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
  labels:
    app: app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: app
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      labels:
        app: app
    spec:
      containers:
        - name: app
          image: app:1.0.0
          ports:
            - containerPort: 3000
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: db-secret
                  key: url
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 512Mi
          readinessProbe:
            httpGet:
              path: /health
              port: 3000
            initialDelaySeconds: 5
            periodSeconds: 10
          livenessProbe:
            httpGet:
              path: /health
              port: 3000
            initialDelaySeconds: 15
            periodSeconds: 20
          # Optional: holds off liveness/readiness until slow startup finishes
          startupProbe:
            httpGet:
              path: /health
              port: 3000
            failureThreshold: 30
            periodSeconds: 5
          securityContext:
            runAsNonRoot: true
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
            seccompProfile:
              type: RuntimeDefault

Native Sidecar Container (GA in 1.33)

spec:
  initContainers:
    - name: log-shipper
      image: fluent/fluent-bit:3.2
      restartPolicy: Always   # makes it a sidecar: starts before, stops after the app
  containers:
    - name: app
      image: app:1.0.0

Sidecars started this way do not block Job completion and are stopped after the main containers exit.

Pod Security Admission (replaces PodSecurityPolicy)

apiVersion: v1
kind: Namespace
metadata:
  name: app
  labels:
    pod-security.kubernetes.io/enforce: restricted   # privileged | baseline | restricted
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/audit: restricted

PodDisruptionBudget

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: app
spec:
  minAvailable: 2        # or maxUnavailable: 1
  selector:
    matchLabels:
      app: app

Service

apiVersion: v1
kind: Service
metadata:
  name: app
spec:
  selector:
    app: app
  ports:
    - port: 80
      targetPort: 3000
  type: ClusterIP

Ingress

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: app
  annotations:
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - app.example.com
      secretName: app-tls
  rules:
    - host: app.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: app
                port:
                  number: 80

ingress-nginx is retired

The community ingress-nginx controller (the one the nginx.ingress.kubernetes.io/* annotations above belong to) was retired by Kubernetes SIG Network, with best-effort maintenance ending in March 2026: no further releases or security fixes. The Ingress API itself is still GA but frozen. For new work use the Gateway API (below) or another maintained Ingress controller; annotations are controller-specific and do not carry over.

Gateway API (HTTPRoute)

apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: web
spec:
  gatewayClassName: my-gateway-class   # provided by your controller (Envoy Gateway, Istio, Cilium, cloud LB...)
  listeners:
    - name: https
      protocol: HTTPS
      port: 443
      hostname: app.example.com
      tls:
        certificateRefs:
          - name: app-tls
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: app
spec:
  parentRefs:
    - name: web
  hostnames: ["app.example.com"]
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /
      backendRefs:
        - name: app
          port: 80

Gateway API CRDs are not installed by default: kubectl get crd gateways.gateway.networking.k8s.io to check.

CronJob

apiVersion: batch/v1
kind: CronJob
metadata:
  name: cleanup
spec:
  schedule: "0 2 * * *"
  timeZone: "Etc/UTC"        # GA since 1.27; default is the controller's local time zone
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 3
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: cleanup
              image: app:1.0.0
              command: ["node", "scripts/cleanup.js"]

HPA

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: app
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: app
  minReplicas: 2
  maxReplicas: 20
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300

NetworkPolicy

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: app-policy
spec:
  podSelector:
    matchLabels:
      app: app
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - port: 3000
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: database
      ports:
        - port: 5432

Debugging Pods

Pod Status Meanings

StatusMeaningAction
PendingWaiting for schedulingCheck node resources, taints, PVC binding
ContainerCreatingPulling image or mounting volumesCheck image name, pull secrets, PVC
RunningAll containers startedCheck readiness probe if not receiving traffic
CrashLoopBackOffContainer crashing repeatedlyCheck logs: kubectl logs pod --previous
ImagePullBackOffCannot pull imageCheck image name, registry credentials
OOMKilledContainer exceeded its memory limit (a termination reason, shown in STATUS)Increase memory limit or fix the leak
CreateContainerConfigErrorReferenced ConfigMap/Secret/key missingkubectl describe pod, check names and keys
Init:0/1, Init:CrashLoopBackOffInit container not finished / failingkubectl logs pod -c init-name
CompletedContainer exited 0Normal for Jobs; for Deployments the process should not exit
EvictedNode under resource pressureCheck node resources, set resource requests
TerminatingBeing deletedCheck finalizers if stuck

Debug Flowchart

Pod not running?
 |
 +-- Status: Pending
 |    +-- kubectl describe pod -> check Events
 |    +-- No nodes available? Check resources, taints, affinity
 |    +-- PVC pending? Check StorageClass, PV availability
 |
 +-- Status: CrashLoopBackOff
 |    +-- kubectl logs pod --previous
 |    +-- Exit code 1? Application error
 |    +-- Exit code 137? SIGKILL - usually OOMKilled (check lastState.terminated.reason)
 |    +-- Exit code 143? SIGTERM - killed by liveness probe or shutdown
 |    +-- Exit code 0? Check restartPolicy
 |
 +-- Status: ImagePullBackOff
      +-- Image name correct?
      +-- Tag exists in registry?
      +-- imagePullSecrets configured?

Debugging Commands

# Check why pod is pending
kubectl describe pod pod-name | grep -A 20 Events

# Check node resources
kubectl describe node node-name | grep -A 5 "Allocated resources"

# DNS debugging
kubectl run debug --image=busybox --rm -it --restart=Never -- nslookup service-name

# Network debugging
kubectl run debug --image=nicolaka/netshoot --rm -it --restart=Never -- bash

# Check if endpoint exists (v1 Endpoints, deprecated since 1.33)
kubectl get endpoints service-name

# Same via EndpointSlices (current API). Empty = selector matches no ready pods
kubectl get endpointslices -l kubernetes.io/service-name=service-name

# Events for a pod, newest last
kubectl events --for pod/pod-name

# Why was the last container killed?
kubectl get pod pod-name -o jsonpath='{.status.containerStatuses[*].lastState.terminated}'

# Check resource usage
kubectl top pods
kubectl top nodes

Resource Requests & Limits

Guidelines

ResourceRequestLimit
CPUSet to average usage2-5x request or no limit
MemorySet to working set size1.5-2x request (many teams set limit = request to avoid OOM kills under node pressure)

CPU over the limit is throttled; memory over the limit is OOM-killed. QoS class: Guaranteed (requests = limits for every container), Burstable (some requests), BestEffort (none, evicted first). Check with kubectl get pod p -o jsonpath='{.status.qosClass}'.

CPU Units

ValueMeaning
11 vCPU core
500m0.5 vCPU core
100m0.1 vCPU core

Memory Units

ValueMeaning
128Mi128 mebibytes
1Gi1 gibibyte
512M512 megabytes (base 10)

Service Types

TypeAccessUse Case
ClusterIPInternal onlyService-to-service communication
NodePortExternal via node IP:portDevelopment, simple access
LoadBalancerExternal via cloud LBProduction external services
ExternalNameDNS CNAME aliasAccess external services
Headless (clusterIP: None)DNS returns pod IPs directlyStatefulSets, client-side load balancing

In-cluster DNS name: service.namespace.svc.cluster.local (pods: pod-name.service.namespace.svc.cluster.local for StatefulSets).


Label Selectors

# Equality-based
kubectl get pods -l app=web
kubectl get pods -l app=web,tier=frontend
kubectl get pods -l 'app!=web'

# Set-based
kubectl get pods -l 'app in (web, api)'
kubectl get pods -l 'app notin (db)'
kubectl get pods -l 'tier'
kubectl get pods -l '!tier'

When to Use X vs Y

DecisionChoice AChoice BUse A WhenUse B When
WorkloadDeploymentStatefulSetStateless appsDatabases, need stable identity
WorkloadDeploymentDaemonSetN replicas on scheduler's choiceOne pod per node (agents, logs)
ConfigConfigMapSecretNon-sensitive configurationPasswords, keys, tokens
ServiceClusterIPLoadBalancerInternal communicationExternal traffic
ScalingHPAVPAScale horizontally (add pods)Scale vertically (bigger pods)
NetworkingIngressService LoadBalancerHTTP routing, multiple hostsTCP/UDP, single service
L7 routingGateway APIIngressNew setups, header/weight routing, role separationExisting setups on a maintained Ingress controller
ProbesreadinesslivenessGate traffic until readyRestart a hung process (keep it cheap and dependency-free)
PackageHelmKustomizeComplex apps, conditional logicOverlays, patch-based config

Useful Aliases

alias k='kubectl'
alias kgp='kubectl get pods'
alias kgs='kubectl get svc'
alias kgd='kubectl get deployments'
alias kgi='kubectl get ingress'
alias kga='kubectl get all'
alias kdp='kubectl describe pod'
alias kl='kubectl logs'
alias klf='kubectl logs -f'
alias ke='kubectl exec -it'
alias kaf='kubectl apply -f'
alias kdf='kubectl delete -f'
alias kctx='kubectl config use-context'
alias kns='kubectl config set-context --current --namespace'

Test Yourself
  1. What command sets the default namespace for your current context? kubectl config set-context --current --namespace=ns

  2. How do you get pods from all namespaces? kubectl get pods -A

  3. What command shows detailed information and recent events for a pod? kubectl describe pod pod-name

  4. How do you view the logs of a crashed container's previous run? kubectl logs pod-name --previous

  5. What command rolls back a deployment to the previous revision? kubectl rollout undo deployment app

  6. How do you forward local port 8080 to a service's port 80? kubectl port-forward svc/service 8080:80

  7. What is the short name for HorizontalPodAutoscaler in kubectl? hpa

  8. What pod status means the container keeps crashing and restarting? CrashLoopBackOff

  9. How do you apply all YAML files in a directory? kubectl apply -f ./dir/

  10. What command creates a secret from a literal key-value pair? kubectl create secret generic s --from-literal=k=v

Common Gotchas

  • Not setting resource requests and limits. Pods without requests can be scheduled on an overcommitted node and get OOMKilled. Always set both.
  • kubectl delete ns deletes everything in that namespace. There is no confirmation prompt by default and no undo. Triple-check, or use kubectl delete ns x -i (interactive).
  • Forgetting readiness probes. Without them, traffic is sent to pods before the app is ready, causing 502 errors during deployments.
  • Using latest image tag in Kubernetes. The imagePullPolicy defaults to Always for latest, causing unexpected image pulls and non-reproducible deployments. Pin versions.
  • Ignoring CrashLoopBackOff exit codes. Exit code 137 means the container got SIGKILL, most often OOMKilled (confirm with lastState.terminated.reason, then increase the memory limit); exit code 1 means application error (check kubectl logs --previous).
  • Liveness probes that check dependencies. If /health calls the database, a DB blip restarts every pod at once. Liveness should only check the process itself.
  • Changing a ConfigMap does not restart pods. Env vars are read at start; mounted files update after a delay (never for subPath mounts). Run kubectl rollout restart or hash the config into a pod annotation.
  • Copying old manifests. extensions/v1beta1, PodSecurityPolicy and batch/v1beta1 are gone; kubectl apply fails with "no matches for kind".

One-Liner Summary

Kubernetes is a container orchestrator that automates deployment, scaling, and self-healing -- master kubectl describe, logs --previous, and resource requests/limits to debug 90% of production issues.