Cheat Sheet

Docker & kubectl

Flags and subcommands you retype daily, each with the gotcha. Docker syntax was checked against Docker 29.4.1 help output; kubectl against the Kubernetes docs and source.

10
Groups
29.4.1
Docker checked
kubectl
Docs checked
Index ยท Spring ยท SQL ยท Git ยท Docker/kubectl ยท Kafka/Rabbit CLI ยท Redis ยท Big-O
01
Chapter 1 - docker run

Starting Containers

Flags were checked against docker run --help on Docker 29.4.1. docker run IMAGE = create + start; put options before the image name, the command and its arguments after it.

FlagMeaningGotcha
-d, --detachRun in the backgroundWithout it the container is tied to your terminal
-it-i keep stdin open, -t allocate a TTYNeeded for shells; do not use -t in scripts piping output
--rmRemove the container when it exitsCombine with -it for throw-away shells; it also removes anonymous volumes
--name webFixed container nameNames must be unique, even for stopped containers
-p 8080:80Publish host port 8080 to container port 80Format is host:container; 127.0.0.1:8080:80 limits it to localhost; -P publishes all EXPOSEd ports to random ports
-e KEY=value, --env-file fSet environment variablesValues passed with -e show in docker inspect and process lists
-v name:/dataMount a named volumeA path starting with / or ./ is a bind mount instead
-v $(pwd):/app, --mountBind-mount a host folder; --mount is the explicit form-v creates a missing host folder; --mount errors instead
--network netAttach to a user-defined networkOn a user-defined network containers reach each other by name; the default bridge has no name resolution
--restart unless-stoppedRestart policyalways also restarts after you stopped it when the daemon restarts
-m 512m, --cpus 1.5Memory and CPU limitsExceeding memory gets the process OOM-killed (exit 137)
-u 1000:1000Run as a non-root userMounted files keep host ownership
--read-onlyRead-only root filesystemAdd --tmpfs /tmp or a volume for paths that must be written
--entrypointOverride the image entrypointThe command after the image becomes the arguments
--pull alwaysPull the image before runningDefault is to use a local copy if present; latest can be stale
-w /appWorking directoryOverrides the image WORKDIR
--platform linux/amd64Run an image for another architectureEmulated on Apple silicon and slow
--health-cmd, --health-intervalDefine a health check at run timeThe status shows in docker ps but nothing restarts the container by itself
02
Chapter 2 - Inspect and operate

Looking Inside Containers

Day-to-day commands for running containers.

CommandWhat it doesGotcha
docker ps -aList containers; -a includes stopped-q prints only ids, --filter status=exited narrows, --format templates the output
docker logs -f --tail 100 cFollow the last 100 log lines--since 10m and -t (timestamps) exist; only stdout and stderr are captured
docker exec -it c shOpen a shell in a running containerContainer must be running; use bash only if the image has it; -u root for a root shell
docker inspect cFull JSON for a container, image, volume or network-f "{{.State.ExitCode}}" extracts one field
docker stats --no-streamOne snapshot of CPU and memory per containerWithout --no-stream it refreshes forever
docker top cProcesses inside the containerShows host PIDs
docker cp c:/path ./dirCopy files between container and hostWorks on stopped containers too
docker stop / kill / restartGraceful (SIGTERM, then SIGKILL after a timeout) / immediate / bothIf your process ignores SIGTERM, stop takes the full timeout; PID 1 signal handling matters (--init)
docker rm -f cRemove a container, stopping it first-v also removes its anonymous volumes
docker eventsLive stream of daemon eventsUseful to see OOM kills and health changes
Exit codes0 success, 137 killed (SIGKILL or OOM), 143 SIGTERM, 139 segfaultCheck docker inspect -f "{{.State.OOMKilled}}" c for 137
03
Chapter 3 - Images and build

Building and Shipping

docker build is the BuildKit-based builder (buildx) in current Docker.

CommandWhat it doesGotcha
docker build -t name:tag .Build from the Dockerfile in the current directoryThe . is the build context; everything in it is sent unless .dockerignore excludes it
-f path/DockerfileUse a different DockerfileContext is still the last argument
--build-arg KEY=vPass a build-time ARGNot for secrets: it stays in image history; use --secret
--target stageStop at a named stage of a multi-stage buildGood for a test or debug stage
--no-cacheIgnore the layer cacheSlow; use only when a cached step is stale (for example a RUN apt-get)
--platform linux/amd64,linux/arm64Build for several platformsNeeds --push or a suitable builder; --load loads a single platform locally
--push / --loadShorthand outputs: push to registry / load into the local daemonPick one
--secret id=npm,src=.npmrcMount a secret for one build stepDoes not end up in a layer when used with RUN --mount=type=secret
docker tag src dstAdd another name to an imageNo copy happens; tags are pointers
docker push / pullUpload / download an imageYou must docker login and the name must include the registry host
docker images / docker image lsList local images<none> entries are dangling layers
docker image history imgShow layers and their sizesReveals what each RUN added
docker save -o f.tar img / docker load -i f.tarExport / import an image as a tar fileFor air-gapped moves; export and import are for containers and lose metadata
docker image prune [-a]Remove dangling images; -a all unusedCheck what is "unused" before -a
04
Chapter 4 - Volumes, networks, compose, cleanup

Storage, Networking and Compose

Compose commands are docker compose (a plugin) in current Docker, not docker-compose.

CommandWhat it doesGotcha
docker volume ls / create / inspect / rmManage named volumesRemoving a volume deletes its data permanently
docker volume pruneRemove unused local volumes-a also removes unused named volumes; without it only anonymous ones
docker network ls / create / inspect / connectManage networksCreate a user-defined network for name-based discovery
docker system pruneRemove stopped containers, unused networks, dangling images and build cache-a all unused images, --volumes also anonymous volumes; ask for -f only in scripts
docker compose up -dCreate and start all services in the background--build rebuilds images, --force-recreate recreates containers, --wait waits for healthy
docker compose downStop and remove containers and networks-v also removes named volumes, --remove-orphans removes leftover services
docker compose logs -f svcFollow a service logOmit the service for all of them
docker compose psList the project's containersShows state and health
docker compose exec svc shShell in a running servicerun starts a new one-off container instead
docker compose configRender the merged, interpolated fileFirst stop when env variables or overrides misbehave
docker compose watchRebuild or sync on file changes (dev loop)Needs a develop.watch section in the compose file
docker context ls / useSwitch between Docker daemonsEasy to run a command against the wrong host
05
Chapter 5 - kubectl: look

Reading Cluster State

Commands from the Kubernetes quick reference (kubernetes.io, main branch). -n ns picks a namespace, -A means all namespaces, -o wide|yaml|json|name changes the output.

CommandWhat it doesGotcha
kubectl config get-contexts / current-contextList contexts / show the active oneCheck before every destructive command
kubectl config use-context nameSwitch clusterApplies to every terminal sharing the kubeconfig
kubectl config set-context --current --namespace=nsSet the default namespaceForgetting this is why get pods shows nothing
kubectl get pods -o widePods with node and IP-A all namespaces, -w watch, --show-labels, -l app=x label selector
kubectl get pod p -o yamlFull object definition and statusIncludes server-added fields; strip them before re-applying
kubectl describe pod pHuman summary plus recent eventsEvents section answers most "why Pending" questions
kubectl get events --sort-by=.metadata.creationTimestampEvents oldest to newestkubectl events --types=Warning shows only warnings
kubectl logs p [-c container]Container log--previous shows the crashed instance; -f follows; -l app=x by label; --tail, --since, --all-containers
kubectl logs deploy/nameLog of one pod of a DeploymentPicks a single pod; use -l to see all
kubectl top pod / top nodeCPU and memory usageNeeds metrics-server installed; --containers, --sort-by=cpu
kubectl explain pod.spec.containersBuilt-in field documentationWorks for custom resources too
kubectl api-resourcesList resource kinds, short names and scope--namespaced=false for cluster-wide kinds
kubectl get -o jsonpath='{.items[*].metadata.name}'Extract fieldsQuote the expression for your shell
kubectl get pods --field-selector=status.phase=RunningFilter by fieldOnly a few fields are supported
kubectl diff -f file.yamlShow what apply would changeRun before apply in production
06
Chapter 6 - kubectl: change

Changing the Cluster

Declarative (apply) is the default way; imperative commands are for quick fixes and debugging.

CommandWhat it doesGotcha
kubectl apply -f file.yamlCreate or update from a manifest (also -f dir)--server-side runs apply on the server with field ownership; --force-conflicts takes ownership on conflicts
kubectl create deployment web --image=nginxQuick imperative create--dry-run=client -o yaml prints a manifest you can edit
kubectl delete -f file.yamlDelete what a manifest describeskubectl delete pod p --now skips the grace period
kubectl scale deploy/web --replicas=3Change replica countA HorizontalPodAutoscaler may scale it back
kubectl set image deploy/web c=img:v2Roll out a new imageContainer name before the = must match
kubectl rollout status deploy/webWait for a rollout to finishAlso -w, --timeout; non-zero exit on failure, good for CI
kubectl rollout history deploy/webList revisions--revision=2 shows one
kubectl rollout undo deploy/web [--to-revision=2]Roll backOnly works for Deployments with kept history (revisionHistoryLimit)
kubectl rollout restart deploy/webRolling restartTypical way to pick up a changed ConfigMap or Secret
kubectl edit deploy/webEdit the live object in your editorChanges are not in Git; apply from files instead
kubectl patch deploy/web -p '{"spec":{"replicas":2}}'Small change by merge patch--type=json for precise JSON patch operations
kubectl label / annotateAdd key=value; remove with key---overwrite to change an existing value
kubectl wait --for=condition=Ready pod/p --timeout=60sBlock until a condition is metHandy in scripts and CI
kubectl autoscale deploy/web --min=2 --max=10Create a HorizontalPodAutoscalerNeeds metrics and CPU requests on the pods
07
Chapter 7 - kubectl: debug and operate nodes

Debugging and Maintenance

Interactive access and node care.

CommandWhat it doesGotcha
kubectl exec -it p -- shShell in a pod-c container when there are several; the -- separates kubectl flags from the command
kubectl run tmp -it --rm --image=busybox:1.28 -- shThrow-away pod for testing from inside the cluster--rm deletes it on exit
kubectl debug p -it --image=busybox:1.28Add an ephemeral debug container to a podWorks on images with no shell; kubectl debug node/n -it --image=... debugs a node
kubectl port-forward svc/web 8080:80Local port to a Service or pod (also pod/p, deploy/d)Forwards to one pod, not load-balanced; stops when the pod restarts
kubectl cp ns/p:/tmp/f ./fCopy files to or from a podNeeds tar in the container
kubectl auth can-i delete pods -n nsCheck your permissions--list shows everything you may do; add --as user to test another identity
kubectl cordon nodeMark a node unschedulableExisting pods keep running
kubectl drain node --ignore-daemonsets --delete-emptydir-dataEvict pods for maintenanceRespects PodDisruptionBudgets; the two flags are required for typical nodes; --timeout, --force, --grace-period exist
kubectl uncordon nodeMake the node schedulable againForgotten uncordon leaves capacity unused
kubectl taint nodes n key=value:NoScheduleRepel pods without a tolerationRemove with key=value:NoSchedule-
kubectl cluster-infoControl plane and DNS addressescluster-info dump for a full state dump
08
Chapter 8 - Reading failures

Pod Status Decoder

The status column is a symptom; the Events section of describe is usually the cause.

Pod status you seeUsually meansFirst command
PendingNot scheduled: no node fits (resources, taints, affinity) or volume not boundkubectl describe pod p then read Events
ImagePullBackOff / ErrImagePullWrong image name or tag, or missing pull credentialskubectl describe pod p
CrashLoopBackOffContainer starts and exits repeatedlykubectl logs p --previous
OOMKilled (in last state)Memory limit exceededkubectl describe pod p, raise the limit or fix the leak
CreateContainerConfigErrorMissing ConfigMap or Secret keykubectl describe pod p
Running but not ReadyReadiness probe failingkubectl describe pod p, check probe and logs
Terminating foreverFinalizer or stuck processkubectl get pod p -o yaml and look at finalizers
09
Chapter 9 - Common mistakes

Docker and kubectl Mistakes

โš  The ones that cost real time
  • **Running kubectl delete on the wrong context or namespace.** Check kubectl config current-context and -n.
  • **docker run image command -p 80:80.** Options after the image name become arguments to the command.
  • **Using the latest tag.** What you tested may not be what runs; pin a version or digest.
  • **Secrets in ENV, --build-arg or the image.** They stay in layers and inspect output; use runtime secrets or --secret.
  • **Expecting docker stop to be instant.** Without SIGTERM handling it waits the full timeout then kills.
  • **docker system prune -a --volumes on a shared host.** Deletes other people's unused images and data.
  • **kubectl edit on production.** Not reproducible; change the manifest and apply.
  • **kubectl logs of a crash-looping pod without --previous.** You see the fresh, empty instance.
  • **Draining a node without --ignore-daemonsets.** The drain refuses and stops.
  • **Treating port-forward as a service.** It is a debugging tunnel to a single pod.
10
Chapter 10 - Go deeper

Long-form pages and what was checked

TopicPage
Docker: images, layers, networking, securityDocker
Kubernetes objects: Pods, Deployments, ServicesKubernetes Core
Probes, autoscaling, upgrades, troubleshootingKubernetes Operations
Linux and shell basicsLinux & Shell Essentials
Rollouts and strategiesDeployment Strategies
Version note

Checked on 2026-10-31: all Docker flags and subcommands in chapters 1 to 4 against --help output of Docker 29.4.1 (client) run locally, including the volume prune -a and system prune --volumes semantics and the compose up and compose down flags; kubectl command shapes against the Kubernetes kubectl quick reference (kubernetes.io, main branch) and flag names of drain, auth can-i, wait, logs, rollout status and apply --server-side against the kubectl source in the Kubernetes repository (master). kubectl was not installed locally, so no kubectl command was executed; Kubernetes version differences are not tracked here (see the Kubernetes docs for your cluster version). Exit-code meanings (137, 143, 139) are standard Linux signal conventions rather than Docker-specific documentation.