Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 78 ยท Practice

Kubernetes Cheat Sheet

One-page Kubernetes cheat sheet: kubectl commands, manifest skeletons, probes, resources, selectors, rollout and RBAC commands and a troubleshooting table of status messages.

This page is a quick reference for what you look up most often while working with Kubernetes: kubectl commands, manifest skeletons, probe and resource settings, selector syntax and a table that maps pod statuses to their usual causes. It assumes you know the ideas; each section links to the lesson that explains them.

There is no cluster on this site, so every command and manifest below is read-only. Two runnable Python stand-ins model the two rules people most often get wrong: resource quantity units and label selectors. They are models of the logic, not Kubernetes.

Pick the right tool

Look get, describe, logs, events.
Change apply, edit, patch, scale, set.
Debug exec, port-forward, debug, top.
Access auth can-i, config, create role.
1 / 2

kubectl basics

Terminal
kubectl config get-contexts                 # list contexts
kubectl config use-context NAME             # switch cluster
kubectl config set-context --current --namespace=NS
kubectl api-resources                       # kinds, short names, namespaced?
kubectl explain pod.spec.containers --recursive

See kubectl Essentials.

Inspect

Command Use
kubectl get pods -A -o wide All namespaces, with node and IP
kubectl get pods --show-labels Check label spelling
kubectl get pods -l app=web,tier!=db Filter by selector
kubectl get pod NAME -o yaml Full object, including status
kubectl get pod NAME -o jsonpath='{.status.podIP}' Extract one field
kubectl get events --sort-by=.lastTimestamp Recent events, oldest first
kubectl describe pod NAME Spec, conditions and Events
kubectl logs NAME -c CONTAINER -f --tail=50 Follow logs of one container
kubectl logs NAME --previous Logs of the crashed instance
kubectl top pod / kubectl top node Live usage (needs metrics-server)

Create and change

Command Use
kubectl apply -f file.yaml (or -f dir/, -k overlay/) Declarative create or update
kubectl diff -f file.yaml Preview the change
kubectl apply --dry-run=server -f file.yaml Validate against the live API
kubectl create deployment web --image=nginx --replicas=3 Imperative create
kubectl run tmp --image=busybox -it --rm -- sh Throwaway debug pod
kubectl edit deploy/web Edit the live object (prefer files)
kubectl scale deploy/web --replicas=5 Change replica count
kubectl set image deploy/web nginx=nginx:1.27.1 Change one image
kubectl label pod NAME env=prod / kubectl annotate ... Add metadata (key- removes)
kubectl delete -f file.yaml / kubectl delete pod NAME Remove objects
kubectl replace --force -f pod.yaml Recreate an object whose fields are immutable

Rollouts

Terminal
kubectl rollout status deploy/web
kubectl rollout history deploy/web
kubectl rollout undo deploy/web --to-revision=2
kubectl rollout restart deploy/web
kubectl rollout pause deploy/web      # and resume

See Rolling Updates and Rollbacks.

Debugging and access

Terminal
kubectl exec -it POD -c CONTAINER -- sh
kubectl port-forward svc/web 8080:80
kubectl cp POD:/path ./local
kubectl debug POD -it --image=busybox --target=CONTAINER     # ephemeral container
kubectl debug node/NODE -it --image=busybox
kubectl auth can-i create deployments -n NS --as=USER
kubectl cordon NODE; kubectl drain NODE --ignore-daemonsets --delete-emptydir-data; kubectl uncordon NODE

Manifest skeletons

Deployment

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  labels: {app: web}
spec:
  replicas: 3
  selector:
    matchLabels: {app: web}
  strategy:
    type: RollingUpdate
    rollingUpdate: {maxSurge: 1, maxUnavailable: 0}
  template:
    metadata:
      labels: {app: web}            # must match spec.selector
    spec:
      containers:
        - name: web
          image: registry.example.com/web:1.4
          ports: [{containerPort: 8080}]
          envFrom:
            - configMapRef: {name: web-config}
          resources:
            requests: {cpu: 100m, memory: 128Mi}
            limits: {memory: 256Mi}

The selector is immutable after creation and must match the template labels. See Deployments.

Service and Ingress

YAML
apiVersion: v1
kind: Service
metadata: {name: web}
spec:
  selector: {app: web}
  ports:
    - port: 80            # what clients call
      targetPort: 8080    # the container port (number or name)
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata: {name: web}
spec:
  ingressClassName: nginx
  rules:
    - host: shop.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service: {name: web, port: {number: 80}}

ConfigMap, Secret and PVC

YAML
apiVersion: v1
kind: ConfigMap
metadata: {name: web-config}
data: {MODE: prod}
---
apiVersion: v1
kind: Secret
metadata: {name: db}
type: Opaque
stringData: {password: change-me}    # stored base64-encoded, not encrypted
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata: {name: data}
spec:
  accessModes: [ReadWriteOnce]
  resources:
    requests: {storage: 10Gi}
  storageClassName: standard

Job and CronJob

YAML
apiVersion: batch/v1
kind: CronJob
metadata: {name: nightly}
spec:
  schedule: "0 2 * * *"
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 3
  jobTemplate:
    spec:
      backoffLimit: 2
      ttlSecondsAfterFinished: 3600
      template:
        spec:
          restartPolicy: OnFailure
          containers:
            - name: report
              image: registry.example.com/report:1.0

Probes

YAML
startupProbe:                    # gives slow apps time; disables the others until it passes
  httpGet: {path: /healthz, port: 8080}
  failureThreshold: 30
  periodSeconds: 2
readinessProbe:                  # failing = removed from Service endpoints
  httpGet: {path: /ready, port: 8080}
  periodSeconds: 5
  failureThreshold: 3
livenessProbe:                   # failing = container restarted
  httpGet: {path: /healthz, port: 8080}
  periodSeconds: 10
  timeoutSeconds: 2
Type Use when
httpGet The app serves HTTP; 200-399 is healthy
tcpSocket Any TCP server; only checks that it accepts connections
exec Run a command in the container; exit code 0 is healthy
grpc The app implements the gRPC health protocol

Do not make liveness depend on external services. See Probes.

Resources

YAML
resources:
  requests: {cpu: 250m, memory: 256Mi}   # used for scheduling and QoS
  limits:   {cpu: "1",  memory: 512Mi}   # CPU is throttled; memory over limit = OOMKilled
Quantity Meaning
500m, 0.5, 1 CPU: 500 millicores = half a core; 1 = one core
128Mi, 1Gi Memory in mebibytes / gibibytes (powers of 1024)
128M, 1G Memory in megabytes / gigabytes (powers of 1000): a classic mix-up
QoS class Rule Evicted
Guaranteed Requests = limits for CPU and memory, in every container Last
Burstable Some request or limit set, not Guaranteed Middle
BestEffort Nothing set First
Python Parse resource quantities

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

See Resource Requests and Limits.

Labels and selectors

Terminal
kubectl get pods -l app=web                 # equality
kubectl get pods -l 'app!=web'              # inequality
kubectl get pods -l 'env in (prod,staging)' # set-based
kubectl get pods -l 'tier notin (db)'
kubectl get pods -l 'release'               # label exists
kubectl get pods -l '!canary'               # label does not exist
YAML
selector:
  matchLabels: {app: web}                   # all must match
  matchExpressions:
    - {key: env, operator: In, values: [prod, staging]}
    - {key: canary, operator: DoesNotExist}

Operators: In, NotIn, Exists, DoesNotExist. All requirements are combined with AND. Label keys may have an optional prefix and a name of up to 63 characters; values are at most 63 characters, alphanumerics plus -, _ and .. A Service's selector supports equality only. See Labels, Selectors and Annotations.

Python Evaluate selectors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that tier notin (data) also matches pods that have no tier label at all, which surprises many people.

Scheduling and RBAC one-liners

Terminal
kubectl taint nodes NODE key=value:NoSchedule        # add; trailing "-" removes
kubectl label nodes NODE disktype=ssd
kubectl create role pod-reader --verb=get,list --resource=pods -n NS
kubectl create rolebinding rb --role=pod-reader --serviceaccount=NS:SA -n NS
kubectl create clusterrolebinding admin-bind --clusterrole=cluster-admin --user=USER
kubectl auth can-i --list -n NS --as=system:serviceaccount:NS:SA
kubectl get pods -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName

Troubleshooting table

Symptom Usual causes First command
Pending Not enough CPU or memory, untolerated taint, selector or affinity mismatch, unbound PVC kubectl describe pod (Events)
ImagePullBackOff / ErrImagePull Wrong name or tag, missing imagePullSecrets, registry unreachable kubectl describe pod
CrashLoopBackOff App exits on start: bad config, missing env, wrong command kubectl logs --previous
OOMKilled (exit 137) Memory limit too low or a leak kubectl top pod, raise limit
CreateContainerConfigError Missing ConfigMap or Secret key kubectl describe pod
Running but 0/1 ready Readiness probe failing (wrong path or port) kubectl describe pod, probe settings
Service has no endpoints Selector mismatch, pods not Ready, other namespace kubectl get endpointslices
Evicted Node pressure (memory, disk) kubectl describe node
Terminating for long Finalizer, stuck volume, or long grace period kubectl get pod -o yaml (finalizers)
Forbidden Missing RBAC for the user or service account kubectl auth can-i --as=...
Unauthorized Bad or expired credentials kubectl config view, token
Deployment rollout stuck New pods never Ready, quota exhausted, progressDeadlineSeconds hit kubectl rollout status, describe the new pods

For the full decision tree, see the Troubleshooting Playbook.

Handy defaults and limits to remember

  • NodePort range: 30000-32767 by default.
  • ndots:5 in pod DNS means short names try search domains first.
  • Termination: SIGTERM, wait terminationGracePeriodSeconds (default 30), then SIGKILL.
  • A Deployment keeps 10 old ReplicaSets by default (revisionHistoryLimit).
  • Rolling update defaults: maxSurge and maxUnavailable are both 25%.
  • Object names must be valid DNS labels or subdomains (lowercase letters, digits, -).
  • HPA: desired = ceil(current * metric / target), with a 10% tolerance.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between 256Mi and 256M in a memory request?

    Mi is 1024 * 1024 bytes; M is 1,000,000 bytes. The suffixes look similar but are not interchangeable.
  2. 2. Which command shows the output of the previous, crashed container?

    --previous prints logs from the last terminated instance, which is where the error of a CrashLoopBackOff is.
  3. 3. Which selector query also matches pods that do not have the label at all?

    NotIn and != match objects where the key is absent as well. Add the Exists requirement if you only want pods that carry the key.
  4. 4. A pod shows Running but 0/1 ready. Which probe is most likely failing?

    Readiness controls whether the pod is Ready and receives Service traffic. A failing liveness probe restarts the container instead.

Summary

  • Look with get, describe, logs, events; change declaratively with apply; debug with exec, port-forward and debug.
  • Generate manifests with --dry-run=client -o yaml and keep the files in Git.
  • A Deployment's selector must match its template labels; a Service selects pods by equality on labels.
  • Requests drive scheduling and QoS; memory over the limit is OOMKilled; Mi and M differ.
  • Readiness removes a pod from traffic; liveness restarts it; keep liveness local to the app.
  • Status messages point to a cause: read the Events first, then logs with --previous.

Revisit the track from the start with What Is Kubernetes?.