Skip to content
Unverified — AI-generated content. Help verify 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


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

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 allAll resources in namespace
kubectl get events --sort-by=.lastTimestampEvents sorted by time

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

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

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

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

Scaling & Rollouts

CommandDescription
kubectl scale deployment app --replicas=5Scale deployment
kubectl autoscale deployment app --min=2 --max=10 --cpu-percent=80Create HPA
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

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

Common YAML Templates

Deployment

yaml
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

Service

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

Ingress

yaml
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

CronJob

yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: cleanup
spec:
  schedule: "0 2 * * *"
  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

yaml
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

yaml
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
OOMKilledOut of memoryIncrease memory limit
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? OOMKilled - increase memory
 |    +-- Exit code 0? Check restartPolicy
 |
 +-- Status: ImagePullBackOff
      +-- Image name correct?
      +-- Tag exists in registry?
      +-- imagePullSecrets configured?

Debugging Commands

bash
# 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 -- nslookup service-name

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

# Check if endpoint exists
kubectl get endpoints service-name

# 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

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

Label Selectors

bash
# 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
PackageHelmKustomizeComplex apps, conditional logicOverlays, patch-based config

Useful Aliases

bash
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 and no undo. Triple-check before running this.
  • 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 OOMKilled (increase memory limit), exit code 1 means application error (check kubectl logs --previous).

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.

"What I cannot create, I do not understand." — Richard Feynman