Cheat sheet: All cheat sheets
Every cheat sheet on one page: Linux, Docker, Kubernetes, Git, Terraform and Helm, each command broken down part by part.
Every cheat sheet on one page. Use the filter to find a flag, or open one tool’s sheet. Each tool has a folder in the sidebar with a page per section.
Navigate & list13
cd <dir>Linux & shellGo into a folderWhat each part does
cdchange directory (a shell built-in)<dir>relative path (logs) or absolute path (/var/log)
cd ~Linux & shellGo to your home folderWhat each part does
cdchange directory~your home directory (/home/<user>); plain "cd" with no argument does the same
cd ..; cd -Linux & shellGo up one level / back to the previous folderWhat each part does
cd ..".." is the parent of the current folder;thencd -jump back to the folder you were in before (and print it)
pwdLinux & shellShow where you areWhat each part does
pwdprint working directory: the full path of the current folder
lsLinux & shellList filesWhat each part does
lslist the current folder (names only, hidden dot-files not shown)
ls -lLinux & shellLong listing: permissions, owner, size, dateWhat each part does
lslist directory contents-llong format: permissions, links, owner, group, size in bytes, modified date, name
ls -laLinux & shellInclude hidden files (.env, .git …)What each part does
-llong format-a--all: also show entries starting with "." (including . and ..)
Tip ls -lA shows hidden files but leaves out . and ..
Linux & shell cheat sheet →ls -lhLinux & shellLong listing with readable sizesWhat each part does
-llong format-h--human-readable: sizes like 4.0K, 12M, 1.3G instead of bytes (works with -l)
ls -ltrLinux & shellNewest files last (great for log folders)What each part does
-llong format-tsort by modification time, newest first-r--reverse: flip the order, so the newest ends up at the bottom next to your prompt
ls -lhSLinux & shellBiggest files firstWhat each part does
-l -hlong format with readable sizes-Ssort by size, largest first
ls -d */Linux & shellList only sub-foldersWhat each part does
-d--directory: list the folders themselves, not what is inside them*/shell glob that matches only directories
ls -R <dir>Linux & shellList everything below, recursivelytree -L 2 <dir>Linux & shellFolder tree, two levels deepWhat each part does
treedraw the folder structure (install it: apt install tree)-L 2limit depth to 2 levels
Files: create, copy, view, compress42
mkdir -p <path/to/dir>Linux & shellCreate a folder (and parents) in one goWhat each part does
mkdirmake directory-pcreate missing parent folders too; no error if it already exists
touch <file>Linux & shellCreate an empty file / update its timestampWhat each part does
touchcreate the file if missing; if it exists, set its modified time to now
cp <src> <dest>Linux & shellCopy a fileWhat each part does
cpcopy<src>file to copy<dest>new file name, or a folder to copy into
cp -r <src-dir> <dest-dir>Linux & shellCopy a folder with everything in itcp -a <src> <dest>Linux & shellCopy keeping permissions, owner and times (backups)What each part does
-a--archive: recursive + keep symlinks, permissions, ownership and timestamps
cp -i <src> <dest>Linux & shellCopy but ask before overwritingWhat each part does
-i--interactive: prompt before overwriting an existing file
mv <old-name> <new-name>Linux & shellRename a file or foldermv <file1> <file2> <dir>/Linux & shellMove files into a folderWhat each part does
<file1> <file2>one or more sources<dir>/destination folder (the trailing / makes it clear it is a folder)
Tip Add -i to be asked before overwriting, -n to never overwrite.
Linux & shell cheat sheet →rm <file>Linux & shellDelete a fileCautionrm -i <files>Linux & shellDelete, but confirm each fileCautionrm -rf <dir>Linux & shellDelete a folder and everything in itDestructiveWhat each part does
-r--recursive: remove directories and their contents-f--force: never prompt, ignore files that don't exist<dir>double-check this path: there is no undo
Tip Run ls <dir> first. Never run it with a variable that might be empty (rm -rf "$DIR/").
Linux & shell cheat sheet →rmdir <dir>Linux & shellDelete an empty folderln -s <target> <link-name>Linux & shellCreate a symbolic link (shortcut)What each part does
lnmake links-s--symbolic: a symlink pointing to <target> (without -s it makes a hard link)<target>the real file or folder<link-name>the shortcut to create
cat <file>Linux & shellPrint a filecat -n <file>Linux & shellPrint with line numbersless <file>Linux & shellRead a long file page by pageWhat each part does
lessscroll a file: Space/b = page down/up, /text = search, n = next match, G = end, q = quit
head -n 20 <file>Linux & shellFirst lines of a filetail -n 50 <file>Linux & shellLast lines of a fileWhat each part does
tailend of a file-n 50how many lines (default 10); add -f to keep following
wc -l <file>Linux & shellCount lines, words, bytesdiff -u <old-file> <new-file>Linux & shellCompare two filesWhat each part does
diffshow differences (exit 0 = same, 1 = different)-uunified format: - removed lines, + added lines, 3 lines of context
file <file>Linux & shellWhat kind of file is this?stat <file>Linux & shellSize, permissions and timestamps of a fileWhat each part does
statdetailed metadata: size, inode, permissions, access/modify/change times
zip -r <archive>.zip <dir>Linux & shellZip a folderunzip <archive>.zip -d <dir>Linux & shellUnzip into a folderWhat each part does
-d <dir>extract into <dir> instead of the current folder
gzip <file>; gunzip <file>.gzLinux & shellCompress / decompress one fileWhat each part does
gzip <file>replace <file> with <file>.gzgunziprestore the original
tar -tf <archive>.tar.gzLinux & shellList what is inside a tarballgrep -rn "<text>" <dir>Linux & shellSearch text in all files under a folderWhat each part does
grepprint lines matching a pattern-rrecurse into sub-directories-nshow the line number of each match"<text>"the pattern (quote it if it has spaces or special characters)<dir>where to start searching
grep -rni --include="*.yaml" "<pattern>" <dir>Linux & shellCase-insensitive search in one file type onlyWhat each part does
-r -nrecursive, with line numbers-iignore upper/lower case--include="*.yaml"only search files whose name matches the glob"<pattern>"regular expression to find
Tip Useful extras: -l (only file names), -v (lines that do NOT match), -w (whole word), -C 3 (3 lines of context).
Linux & shell cheat sheet →find <dir> -name "*.log" -mtime +7 -deleteLinux & shellFind and delete log files older than 7 daysDestructiveWhat each part does
find <dir>walk the directory tree starting at <dir>-name "*.log"file name matches the pattern (quoted so the shell does not expand it)-mtime +7last modified more than 7 days ago-deletedelete each match
Tip Run it with -print instead of -delete first to see what would go.
Linux & shell cheat sheet →find <dir> -type f -size +100MLinux & shellFind big filesWhat each part does
-type fregular files only (d = directories)-size +100Mlarger than 100 MiB ("+" = more than, "-" = less than)
find <dir> -name "*.tmp" -print0 | xargs -0 rm -fLinux & shellRun a command on every found file (safe with spaces)DestructiveWhat each part does
-print0print each name ending with a NUL byte instead of a newline|pipe the names to xargsxargs -0read NUL-separated names, so spaces/newlines in names are saferm -fremove the files, no prompts
tail -F <file> | grep --line-buffered "<word>"Linux & shellFollow a log and show only matching linesWhat each part does
tailshow the end of a file-Ffollow new lines and keep following when the file is rotated or recreated|stream new lines into grepgrep --line-bufferedprint each match immediately instead of buffering"<word>"text to look for, e.g. ERROR
sed -n '<start>,<end>p' <file>Linux & shellShow lines N to M of a fileWhat each part does
sedstream editor-ndon't print every line automatically'<start>,<end>p'address range (line numbers) + p = print those lines
sed -i.bak 's/<old>/<new>/g' <file>Linux & shellReplace text in a file in place (keep a backup)CautionWhat each part does
-i.bakedit the file in place and save the original as <file>.baks/<old>/<new>/substitute: regex <old> → <new>greplace every match on a line, not just the first
sort <file> | uniq -c | sort -rn | headLinux & shellCount duplicate lines, most frequent firstWhat each part does
sort <file>sort lines so duplicates sit next to each otheruniq -ccollapse adjacent duplicates and prefix each with its countsort -rnsort by that number (-n numeric) in reverse order (-r)headtop 10
awk '{print $1}' access.log | sort | uniq -c | sort -rn | headLinux & shellTop client IPs in an access logWhat each part does
awk '{print $1}'print the first whitespace-separated field of every line (the client IP)sort | uniq -cgroup identical IPs and count themsort -rn | headhighest counts first, top 10
grep -c "<pattern>" <file>; wc -l <file>Linux & shellCount lines / matchesWhat each part does
grep -ccount matching lines instead of printing themwc -lcount all lines in the file
sort -t: -k3,3n /etc/passwdLinux & shellSort a delimited file by a numeric columnWhat each part does
-t:fields are separated by ":"-k3,3sort key is field 3 onlyncompare that key as a number
tar -czvf <name>.tar.gz <dir>Linux & shellCreate a gzip tarballWhat each part does
-ccreate an archive-zcompress with gzip-vlist files as they are added-f <name>.tar.gzarchive file name (must come right after f)
tar -xzvf <name>.tar.gz -C <dest>Linux & shellExtract a tarball into a folderWhat each part does
-xextract-z -v -fgzip, verbose, archive file-C <dest>change to <dest> before extracting
rsync -avzn --delete <src>/ <user>@<host>:<dest>/Linux & shellSync a folder to a server (preview first)CautionWhat each part does
-aarchive mode: recursive, keep permissions, times, owner, symlinks-vverbose-zcompress during transfer-ndry run: show what would change. Remove it to really sync--deletedelete files on the destination that are not in the source<src>/trailing slash = copy the folder’s contents, not the folder itself
scp -r -P <port> <src> <user>@<host>:<path>Linux & shellCopy a folder to a server over SSHWhat each part does
-rcopy directories recursively-P <port>SSH port (capital P; lowercase -p means preserve times)<user>@<host>:<path>remote destination
Error codes & fixes55
curl -sSIL <url>301 / 302Error codes & fixesRedirect: see every hopWhat it means
301 Moved Permanently / 302 Found: the resource is at another URL, given in the
Locationheader. Not an error by itself.Usual causes & fixes
- Redirect loop (ERR_TOO_MANY_REDIRECTS): HTTP→HTTPS redirect behind a load balancer that terminates TLS. The app sees HTTP every time; trust
X-Forwarded-Proto. - Wrong host or missing trailing slash in the
Locationheader. - Old path after a move: update the link or add a permanent redirect.
Diagnose: what each part of the command does
curlmake an HTTP request-s -Sno progress bar, but still show errors-Iheaders only (HEAD request)-Lfollow redirects, printing the headers of every hop<url>the address you are testing
- Redirect loop (ERR_TOO_MANY_REDIRECTS): HTTP→HTTPS redirect behind a load balancer that terminates TLS. The app sees HTTP every time; trust
curl -v -X POST -H "Content-Type: application/json" -d @<file>.json <url>400Error codes & fixesBad Request: look at exactly what you sendWhat it means
The server will not process the request because of a client error: malformed syntax, invalid framing, bad parameters.
Usual causes & fixes
- Invalid JSON: check it with
jq . <file>.json. - Missing or wrong
Content-Typeheader. - Headers or cookies too large (nginx: "Request Header Or Cookie Too Large" → raise
large_client_header_buffers). - Required field missing: read the response body, APIs usually say which one.
Diagnose: what each part of the command does
-vverbose: print request and response headers-X POSTHTTP method-H "Content-Type: application/json"tell the server the body is JSON-d @<file>.jsonsend the body from a file (@ = read file)
- Invalid JSON: check it with
curl -i -H "Authorization: Bearer <token>" <url>401Error codes & fixesUnauthorized: test the credentialsWhat it means
"Unauthenticated": the request has no valid credentials. The
WWW-Authenticateresponse header says which scheme is expected.Usual causes & fixes
- Token missing, expired or for the wrong environment.
- Wrong scheme: Bearer vs Basic vs an API-key header.
- Clock skew makes a fresh JWT look expired/not-yet-valid: check
timedatectl. - A proxy (basic auth, oauth2-proxy) in front of the app asks for its own login.
Diagnose: what each part of the command does
-iinclude response headers in the output-H "Authorization: Bearer <token>"send the token the way the API expects
namei -l <path-to-file>403Error codes & fixesForbidden: check the server log and the file pathWhat it means
The server knows who you are but refuses access.
Usual causes & fixes
- nginx/Apache: the web server user needs
xon every parent folder andron the file (see namei output). Checksudo tail -n 50 /var/log/nginx/error.log. - Folder requested but no index file and autoindex off → 403.
- IP allow/deny list, WAF rule, or a cloud bucket policy.
- Kubernetes API "forbidden": RBAC. Check with
kubectl auth can-i <verb> <resource> -n <namespace>.
Diagnose: what each part of the command does
nameifollow a path one component at a time-llong format: owner, group and permissions of EVERY directory on the way<path-to-file>e.g. /var/www/site/index.html
- nginx/Apache: the web server user needs
curl -sS -o /dev/null -w "%{http_code} %{url_effective}\n" -L <url>404Error codes & fixesNot Found: what does the server actually return?What it means
The server cannot find the requested resource. For an API it can also mean the endpoint exists but the object does not.
Usual causes & fixes
- Typo or wrong path/base path (e.g. app served under /api but called at /).
- nginx
location/root/aliaspoints somewhere else:nginx -T | grep -n -A5 "location". - Kubernetes ingress host or path does not match (see the next entry).
- Static site: file not deployed, or case-sensitive name (Index.html vs index.html).
Diagnose: what each part of the command does
-sSquiet, show errors-o /dev/nulldiscard the body-w "%{http_code} %{url_effective}\n"print the final status and the final URL after redirects-Lfollow redirects
kubectl get ingress -A; kubectl describe ingress <ingress> -n <namespace>404Error codes & fixesNot Found behind a Kubernetes ingressWhat it means
The ingress controller answered but no rule matched the host + path (often the controller's default 404 page).
Usual causes & fixes
- Host header does not match the
host:rule (test withcurl -H "Host: <host>" http://<ingress-ip>/<path>). pathType: ExactvsPrefix, or a rewrite annotation changing the path.- Wrong
ingressClassName, so a different controller (or none) owns the ingress.
Diagnose: what each part of the command does
get ingress -Aall ingresses with their HOSTS and ADDRESSdescribe ingress <ingress>rules: host + path → service:port, and events-n <namespace>namespace of the ingress
- Host header does not match the
curl -i -X OPTIONS <url>405Error codes & fixesMethod Not Allowed: which methods are allowed?What it means
The method (GET/POST/PUT…) is known but not supported for this URL.
Usual causes & fixes
- POST to a static location, or GET to a POST-only endpoint.
- A proxy or ingress rule only allows some methods.
- CORS preflight (OPTIONS) not handled by the API.
Diagnose: what each part of the command does
-ishow response headers-X OPTIONSask the server which methods it supports (Allow header)
grep -rn "client_max_body_size" /etc/nginx/413Error codes & fixesContent Too Large: find the body size limitWhat it means
The request body is larger than the server allows.
Usual causes & fixes
- nginx: raise
client_max_body_size 50m;in the http/server/location block, thensudo nginx -t && sudo systemctl reload nginx. - ingress-nginx: annotation
nginx.ingress.kubernetes.io/proxy-body-size: "50m". - App or framework upload limit as well.
Diagnose: what each part of the command does
grep -rnsearch recursively with line numbers"client_max_body_size"nginx directive that limits upload size/etc/nginx/nginx config folder
- nginx: raise
curl -sI <url> | grep -i -E "retry-after|ratelimit"429Error codes & fixesToo Many Requests: read the rate-limit headersWhat it means
You sent too many requests in a given time (rate limiting).
Usual causes & fixes
- Wait for
Retry-Afterseconds; add backoff with jitter to clients. - Retry storm from many pods sharing one egress IP / API key.
- Docker Hub "toomanyrequests" on image pulls:
docker loginor use a mirror.
Diagnose: what each part of the command does
curl -sIquiet, headers only| grep -i -Ecase-insensitive, extended regex filter"retry-after|ratelimit"Retry-After and X-RateLimit-* headers
- Wait for
kubectl logs <pod> -n <namespace> --tail=100500Error codes & fixesInternal Server Error: read the application logsWhat it means
Generic "the server hit something it does not know how to handle": the app crashed or threw.
Usual causes & fixes
- Unhandled exception: the stack trace is in the app log (
docker logs <container>/journalctl -u <service>). - Bad config or missing env var after a deploy: compare with the previous version, roll back if needed.
- Downstream dependency (DB, cache) down or credentials rotated.
Diagnose: what each part of the command does
kubectl logs <pod>app output (stack traces end up here)-n <namespace>namespace--tail=100last 100 lines
- Unhandled exception: the stack trace is in the app log (
sudo tail -n 50 /var/log/nginx/error.log502Error codes & fixesBad Gateway: the proxy got no valid answer from the appWhat it means
The gateway/proxy received an invalid response from the upstream (your app).
Usual causes & fixes
- App not running or crashed: check
systemctl status <service>/ pod status. - Proxy points to the wrong port (
proxy_pass/ ServicetargetPort). - App listens on 127.0.0.1 inside a container instead of 0.0.0.0.
- TLS mismatch: proxy speaks HTTP to an HTTPS backend or the reverse.
Diagnose: what each part of the command does
sudolog files are root-onlytail -n 50last 50 lines/var/log/nginx/error.lognginx error log: says why the upstream failed (connection refused, reset, …)
- App not running or crashed: check
kubectl get endpointslices -l kubernetes.io/service-name=<service> -n <namespace>502 / 503Error codes & fixesKubernetes service has no ready pods behind itWhat it means
Empty ENDPOINTS = the Service has nowhere to send traffic, so the ingress returns 502/503.
Usual causes & fixes
- Service
selectordoes not match the pod labels: comparekubectl get svc <service> -o yamlwithkubectl get pods --show-labels. - Pods exist but are not Ready: readiness probe failing (
kubectl describe pod <pod>→ Events). targetPortdoes not match the containerPort.
Diagnose: what each part of the command does
get endpointslicesthe pod IPs a Service actually sends traffic to-l kubernetes.io/service-name=<service>only the slices of that Service-n <namespace>namespace
- Service
kubectl get pods -l app=<app> -n <namespace> -o wide503Error codes & fixesService Unavailable: are the pods ready?What it means
The server is not ready to handle the request: down for maintenance or overloaded. Often sent with
Retry-After.Usual causes & fixes
- READY 0/1: readiness probe failing (wrong path/port, app still starting).
- All replicas restarting or scaled to 0.
- Maintenance mode or circuit breaker in the proxy/mesh (Envoy "no healthy upstream").
Diagnose: what each part of the command does
-l app=<app>pods of that app-o wideshow node and IP too
curl -sS -o /dev/null -w "connect=%{time_connect}s ttfb=%{time_starttransfer}s total=%{time_total}s\n" <url>504Error codes & fixesGateway Timeout: how long does the backend take?What it means
The gateway did not get a response from the upstream in time.
Usual causes & fixes
- Backend slower than the proxy timeout: nginx
proxy_read_timeoutdefaults to 60s; cloud load balancers have their own idle timeout. - Slow DB query or external call: check app/DB logs.
- Network path blocked (security group / firewall) so the connect hangs.
Diagnose: what each part of the command does
-o /dev/nulldiscard body%{time_connect}time to open the TCP connection%{time_starttransfer}time to first byte: how long the backend "thought"%{time_total}whole request
- Backend slower than the proxy timeout: nginx
echo | openssl s_client -connect <host>:443 -servername <host> 2>/dev/null | openssl x509 -noout -subject -issuer -datesTLSError codes & fixesCertificate expired / not trusted: inspect the certWhat it means
Errors like "certificate has expired", "unable to get local issuer certificate" or "hostname mismatch" come from the certificate the server presents.
Usual causes & fixes
- Expired: renew (cert-manager / certbot) and reload the server.
- Missing intermediate chain: serve the full chain (fullchain.pem).
- Hostname not in the SAN list, or wrong SNI/default certificate.
Diagnose: what each part of the command does
echo |send an empty request so s_client exitsopenssl s_client -connect <host>:443do a TLS handshake-servername <host>SNI: ask for the certificate of this host name2>/dev/nullhide handshake noiseopenssl x509 -nooutparse the certificate, do not print it-subject -issuer -dateswho it is for, who signed it, valid from / until
echo $?$?Error codes & fixesWhat did the last command return?What it means
Every command returns a number 0-255. 0 means success. CI jobs and
&&use it.Usual causes & fixes
- Check it right after the command; the next command overwrites it.
- In scripts use
set -eto stop on the first failure,set -o pipefailto catch failures inside pipes.
Diagnose: what each part of the command does
echoprint$?exit status of the last command: 0 = success, anything else = failure
bash -x <script>.sh1Error codes & fixesGeneral error: trace the scriptWhat it means
Catch-all for general errors: the program failed and chose 1.
Usual causes & fixes
- Read the last lines of stderr: the real message is usually there.
- A command inside the script failed:
-xshows which one.
Diagnose: what each part of the command does
bashrun the script with bash-xprint every command (with expanded variables) before running it
<command> --help2Error codes & fixesMisuse / wrong argumentsWhat it means
Bash builtins return 2 for incorrect usage (invalid option, missing argument); many tools follow this.
Usual causes & fixes
- Typo in a flag or a missing required argument.
- Shell syntax error in a script.
Diagnose: what each part of the command does
--helpshow valid options and arguments
ls -l <file>; file <file>126Error codes & fixesFound but cannot executeWhat it means
The command exists but is not executable.
Usual causes & fixes
- Missing execute bit:
chmod +x <file>. - Windows line endings in a script:
sed -i 's/\r$//' <file>(or dos2unix). - Filesystem mounted
noexec:findmnt -o TARGET,OPTIONS -T <file>.
Diagnose: what each part of the command does
ls -l <file>check the x permission bitfile <file>check the type: script with CRLF line terminators, wrong binary format…
- Missing execute bit:
command -v <command> || echo "not found; PATH=$PATH"127Error codes & fixesCommand not foundWhat it means
The shell could not find the program in any PATH folder.
Usual causes & fixes
- Not installed (install it with apt/dnf/apk).
- Installed in a folder not on PATH (e.g. ~/.local/bin):
export PATH="$HOME/.local/bin:$PATH". - Typo, or a container image that does not include the tool (distroless, alpine without bash).
Diagnose: what each part of the command does
command -v <command>print where the command is, or nothing if it is not found||if that failed…echo "…PATH=$PATH"…show the folders the shell searches
kill -l $(( <exit-code> - 128 ))128+NError codes & fixesKilled by a signal: which one?What it means
When a process dies from signal N, the shell reports 128+N. E.g. 137 → 9 (KILL), 143 → 15 (TERM), 130 → 2 (INT).
Usual causes & fixes
- Run it with the code you got, e.g.
kill -l $(( 137 - 128 ))prints KILL.
Diagnose: what each part of the command does
kill -l <number>print the signal name for a number$(( … ))shell arithmetic<exit-code> - 128exit codes above 128 mean "terminated by signal N"
- Run it with the code you got, e.g.
kill -l 2130Error codes & fixesStopped with Ctrl+CWhat it means
128 + 2 (SIGINT): someone (or something) pressed Ctrl+C / sent an interrupt.
Usual causes & fixes
- Expected if you stopped it. In CI it usually means the job was cancelled.
Diagnose: what each part of the command does
kill -l 2signal 2 = INT, what Ctrl+C sends
dmesg -T | grep -i -E "out of memory|killed process"137Error codes & fixesKilled (SIGKILL): usually out of memoryWhat it means
128 + 9 (SIGKILL): the process was force-killed. In containers this is almost always the memory limit (OOMKilled).
Usual causes & fixes
- Docker:
docker inspect --format '{{.State.OOMKilled}}' <container>; raise-mor fix the leak. - Kubernetes:
kubectl describe pod <pod>→ Last State: Terminated, Reason: OOMKilled; raiseresources.limits.memory. - A human or script ran
kill -9, or a stop timed out and was escalated.
Diagnose: what each part of the command does
dmesg -Tkernel messages with readable timestampsgrep -i -E "out of memory|killed process"the OOM killer lines
- Docker:
dmesg -T | grep -i segfault139Error codes & fixesSegmentation fault (SIGSEGV)What it means
128 + 11 (SIGSEGV): the program accessed invalid memory and crashed.
Usual causes & fixes
- Bug in a native binary or library; version mismatch between binary and libs (e.g. glibc vs musl/alpine).
- Wrong CPU architecture image under emulation.
Diagnose: what each part of the command does
dmesg -Tkernel loggrep -i segfaultlines about the crash (which binary, which library)
docker inspect --format '{{.State.ExitCode}} {{.State.FinishedAt}}' <container>143Error codes & fixesTerminated (SIGTERM): asked to stopWhat it means
128 + 15 (SIGTERM): a graceful stop request: docker stop, a Kubernetes rollout/scale-down, systemctl stop.
Usual causes & fixes
- Normal during deploys and restarts.
- If unexpected: check who stopped it (events,
kubectl get events, systemd journal). - App should handle SIGTERM and exit cleanly within the grace period (
terminationGracePeriodSeconds, default 30s).
Diagnose: what each part of the command does
docker inspectcontainer details--format '…'print just the exit code and when it stopped
kubectl logs <pod> -n <namespace> --previousCrashLoopBackOffError codes & fixesContainer keeps crashing: read the crashed runWhat it means
Not a phase: the container starts, exits, and Kubernetes keeps restarting it with increasing back-off.
Usual causes & fixes
- App exits at startup: missing env var, bad config, failed DB connection (see the log).
- OOMKilled / exit 137: raise the memory limit.
- Liveness probe kills a slow-starting app: add a startupProbe.
- Wrong command/args in the pod spec.
Diagnose: what each part of the command does
logs <pod>container output--previousfrom the previous (crashed) container, not the one restarting now
kubectl describe pod <pod> -n <namespace> | grep -A 10 EventsImagePullBackOffError codes & fixesImage cannot be pulled: read the pull errorWhat it means
ErrImagePull / ImagePullBackOff: the kubelet could not pull the image and is backing off.
Usual causes & fixes
- Wrong image name or tag (typos, tag never pushed).
- Private registry without
imagePullSecrets. - Registry rate limit (Docker Hub "toomanyrequests") or the node cannot reach the registry.
- Check from your machine:
docker pull <image>:<tag>.
Diagnose: what each part of the command does
describe podfull status| grep -A 10 Eventsjump to the Events and show 10 lines after
kubectl describe pod <pod> -n <namespace>PendingError codes & fixesPod not scheduled: why?What it means
The pod is accepted but not running: usually it cannot be scheduled onto any node.
Usual causes & fixes
- "Insufficient cpu/memory": requests too high or the cluster is full (scale nodes or lower requests).
- "had untolerated taint" / node selector or affinity matches no node.
- PersistentVolumeClaim not bound:
kubectl get pvc -n <namespace>.
Diagnose: what each part of the command does
describe podlook at Events: FailedScheduling explains the reason
kubectl get configmap,secret -n <namespace>CreateContainerConfigErrorError codes & fixesMissing ConfigMap or SecretWhat it means
The container config refers to something that does not exist (usually a ConfigMap/Secret or a key in it).
Usual causes & fixes
- Create the missing ConfigMap/Secret, or fix the name/key in
envFrom/valueFrom. - It exists in another namespace: they are namespaced.
Diagnose: what each part of the command does
get configmap,secretlist both kinds at once
- Create the missing ConfigMap/Secret, or fix the name/key in
kubectl get pod <pod> -n <namespace> -o jsonpath='{.status.containerStatuses[*].lastState.terminated.reason}'OOMKilledError codes & fixesWas the container killed for memory?What it means
The container used more memory than its limit and the kernel killed it (exit code 137).
Usual causes & fixes
- Raise
resources.limits.memory(and requests) or fix the leak; compare withkubectl top pod. - JVM/Node.js heap configured larger than the container limit.
Diagnose: what each part of the command does
-o jsonpath=…print one fieldlastState.terminated.reasonwhy the previous container instance ended (OOMKilled, Error, Completed)
- Raise
kubectl get pods -A --field-selector=status.phase=FailedEvictedError codes & fixesPods evicted from a nodeWhat it means
The kubelet removed pods because the node ran short of memory or disk (or for maintenance).
Usual causes & fixes
- Check node pressure:
kubectl describe node <node>→ Conditions (DiskPressure, MemoryPressure). - Clean them up:
kubectl delete pods -A --field-selector=status.phase=Failed. - Set requests/limits and ephemeral-storage limits so pods are scheduled realistically.
Diagnose: what each part of the command does
-Aall namespaces--field-selector=status.phase=Failedevicted pods end up as Failed
- Check node pressure:
kubectl get events -n <namespace> --sort-by=.lastTimestampContainerCreatingError codes & fixesStuck creating: volume or network problemWhat it means
The pod is on a node but the container has not started yet.
Usual causes & fixes
- FailedMount / FailedAttachVolume: PVC, Secret or ConfigMap volume not available.
- CNI / network sandbox errors: networking plugin problem on that node.
- Very large image still pulling.
Diagnose: what each part of the command does
get eventswhat the scheduler/kubelet reported--sort-by=.lastTimestampnewest last
kubectl auth can-i <verb> <resource> -n <namespace> --as=<user>ForbiddenError codes & fixesRBAC: am I allowed to do this?What it means
"… is forbidden: User … cannot …": the identity has no Role/ClusterRole binding for that action.
Usual causes & fixes
- Add a RoleBinding / ClusterRoleBinding for the user or service account.
- Wrong context or namespace:
kubectl config current-context.
Diagnose: what each part of the command does
auth can-iask the API server whether an action is allowed (yes/no)<verb> <resource>e.g. get pods, create deployments--as=<user>check for another user or service account (system:serviceaccount:<ns>:<name>)
kubectl config current-context && kubectl cluster-infoUnable to connectError codes & fixes"Unable to connect to the server" / "Unauthorized"What it means
kubectl cannot reach or authenticate to the API server.
Usual causes & fixes
- Wrong context, VPN off, or a private API endpoint.
- Expired credentials: refresh the kubeconfig (
aws eks update-kubeconfig,az aks get-credentials,gcloud container clusters get-credentials).
Diagnose: what each part of the command does
config current-contextwhich cluster kubectl is pointing at&&thencluster-infotry to reach the API server
namei -l <path>Permission deniedError codes & fixesWhich part of the path blocks me?What it means
The user lacks the permission needed: r to read, w to write, x to run a file or to enter a folder.
Usual causes & fixes
- Missing x on a parent folder blocks everything below it.
- File belongs to another user:
sudo chown <user>:<group> <path>or add the user to the group. - Script not executable:
chmod +x <file>. - SELinux/AppArmor can deny even when modes look fine:
ls -Z,sudo ausearch -m avc -ts recent.
Diagnose: what each part of the command does
namei -lowner, group and permissions of every folder on the way to <path>
df -h <path>; df -i <path>No space left on deviceError codes & fixesOut of disk space or inodesWhat it means
ENOSPC: the filesystem has no free blocks or no free inodes left.
Usual causes & fixes
- Find big folders:
sudo du -xh --max-depth=1 <path> | sort -rh | head. - Deleted files still open:
sudo lsof -nP +L1(restart the process). - Docker:
docker system dfthen prune; journald:journalctl --vacuum-time=7d.
Diagnose: what each part of the command does
df -h <path>free space on the filesystem holding <path>df -i <path>free inodes: a disk can be "full" with millions of tiny files
- Find big folders:
sudo ss -tlnp | grep :<port>Connection refusedError codes & fixesIs anything listening on that port?What it means
The host answered but nothing accepts connections on that port (or a firewall actively rejects).
Usual causes & fixes
- Service not running:
systemctl status <service>. - Listening only on 127.0.0.1, not 0.0.0.0 / the external IP.
- Wrong port in the client config.
Diagnose: what each part of the command does
ss -tlnpTCP listening sockets with numeric ports and process| grep :<port>only that port
- Service not running:
nc -zv -w 5 <host> <port>Connection timed outError codes & fixesCan I reach the port at all?What it means
No answer at all: packets are dropped on the way.
Usual causes & fixes
- Firewall, security group or network ACL blocks the port.
- Wrong IP / host is down / routing problem (
traceroute <host>).
Diagnose: what each part of the command does
nc -zjust test the connection-vsay succeeded / timed out-w 5give up after 5 seconds
sudo lsof -i :<port>Address already in useError codes & fixesWho holds the port?What it means
EADDRINUSE: another process is already bound to that port.
Usual causes & fixes
- Stop the other process or pick another port.
- Old instance still running (e.g. a previous container:
docker ps --filter publish=<port>).
Diagnose: what each part of the command does
lsof -i :<port>process that has that port open
getent hosts <hostname>Could not resolve hostError codes & fixesDNS: does the name resolve?What it means
"Name or service not known" / "Temporary failure in name resolution": the hostname could not be turned into an IP.
Usual causes & fixes
- Typo, or a private name that only resolves inside a VPN/VPC.
- Broken resolver: check
cat /etc/resolv.conf, test withdig @8.8.8.8 <hostname>. - In Kubernetes use
<service>.<namespace>.svc.cluster.local.
Diagnose: what each part of the command does
getent hostsresolve the name the way the system does (/etc/hosts + DNS)
ulimit -n; grep "open files" /proc/<pid>/limitsToo many open filesError codes & fixesCheck the open-files limitWhat it means
EMFILE: the process hit its maximum number of open file descriptors.
Usual causes & fixes
- Raise it for a service:
LimitNOFILE=65536in the systemd unit, thendaemon-reload+ restart. - A descriptor leak in the app (count them:
ls /proc/<pid>/fd | wc -l).
Diagnose: what each part of the command does
ulimit -nlimit for your current shell/proc/<pid>/limitsthe limits a running process actually has
- Raise it for a service:
findmnt -o TARGET,OPTIONS -T <path>Read-only file systemError codes & fixesWhy is the disk read-only?What it means
The filesystem is mounted read-only, often remounted by the kernel after disk errors.
Usual causes & fixes
- Check kernel errors:
dmesg -T | grep -i -E "error|remount". - Containers: the image filesystem is read-only by design; write to a volume or /tmp.
Diagnose: what each part of the command does
findmnt -T <path>the mount that contains <path>-o TARGET,OPTIONSshow where it is mounted and its options (ro / rw)
- Check kernel errors:
ssh-keygen -R <host>Host key verification failedError codes & fixesServer key changed: remove the old oneCautionWhat it means
The server's SSH host key differs from the one you saved: a rebuilt server, or a man-in-the-middle.
Usual causes & fixes
- Verify the new fingerprint out of band before reconnecting.
- Expected after recreating a VM with the same IP/name.
Diagnose: what each part of the command does
ssh-keygen -R <host>delete the saved key for <host> from ~/.ssh/known_hosts
ssh -v <user>@<host>Permission denied (publickey)Error codes & fixesSSH key rejected: see what ssh triesWhat it means
The server did not accept any of your keys.
Usual causes & fixes
- Wrong user (ubuntu vs ec2-user vs root) or wrong key:
ssh -i <key-file> <user>@<host>. - Permissions too open:
chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys ~/.ssh/id_ed25519(sshd StrictModes refuses group/world-writable files). - Public key not in the server's
~/.ssh/authorized_keys:ssh-copy-id <user>@<host>.
Diagnose: what each part of the command does
-vverbose: shows which keys are offered and why they are refused
- Wrong user (ubuntu vs ec2-user vs root) or wrong key:
sudo usermod -aG docker $USER && newgrp dockerdocker.sock permission deniedError codes & fixes"permission denied while trying to connect to the Docker daemon socket"CautionWhat it means
Your user may not talk to /var/run/docker.sock.
Usual causes & fixes
- Note: the docker group is root-equivalent on that machine.
Diagnose: what each part of the command does
usermod -aG docker $USERadd yourself to the docker group&&thennewgrp dockerstart a shell with the new group (or log out and in)
sudo systemctl status dockerCannot connect to daemonError codes & fixes"Cannot connect to the Docker daemon … Is the docker daemon running?"What it means
The client cannot reach dockerd.
Usual causes & fixes
- Start it:
sudo systemctl enable --now docker. - Wrong
DOCKER_HOSTor context:docker context ls.
Diagnose: what each part of the command does
systemctl status dockeris the Docker service running, and its last log lines
- Start it:
docker ps --filter publish=<port>port is already allocatedError codes & fixesWhich container holds the host port?What it means
Another container (or process) already uses that host port.
Usual causes & fixes
- Stop/remove the other container, or map a different host port (
-p 8081:80). - Not a container?
sudo lsof -i :<port>.
Diagnose: what each part of the command does
--filter publish=<port>containers publishing that host port
- Stop/remove the other container, or map a different host port (
docker image inspect <image> --format '{{.Os}}/{{.Architecture}}'exec format errorError codes & fixesImage built for another CPU architectureWhat it means
The binary in the image does not match the machine's CPU (e.g. an arm64 image on amd64), or a script lacks a shebang.
Usual causes & fixes
- Build for the target:
docker buildx build --platform linux/amd64,linux/arm64 …. - Script entrypoint: add
#!/bin/shas the first line.
Diagnose: what each part of the command does
image inspectimage metadata--format '{{.Os}}/{{.Architecture}}'e.g. linux/arm64 vs linux/amd64
- Build for the target:
docker logintoomanyrequestsError codes & fixesDocker Hub pull rate limitWhat it means
Anonymous pulls from Docker Hub are rate-limited per IP.
Usual causes & fixes
- Log in (also on CI runners / nodes via imagePullSecrets).
- Use a pull-through cache or mirror the images to your own registry.
Diagnose: what each part of the command does
docker loginauthenticated pulls get a higher limit
git pull --rebase origin <branch>rejected (non-fast-forward)Error codes & fixes"Updates were rejected because the remote contains work that you do not have"What it means
Someone pushed to the branch since you last pulled; a plain push would overwrite their work.
Usual causes & fixes
- Pull with rebase, resolve conflicts, then
git push. - Only after a deliberate rebase of your own branch:
git push --force-with-lease.
Diagnose: what each part of the command does
pull --rebasefetch the remote commits and replay yours on toporigin <branch>the branch you are pushing
- Pull with rebase, resolve conflicts, then
git diff --name-only --diff-filter=UCONFLICTError codes & fixesMerge conflict: which files?What it means
Both sides changed the same lines; Git marked them with <<<<<<< ======= >>>>>>>.
Usual causes & fixes
- Edit the files, remove the markers,
git add <file>, thengit commit(orgit rebase --continue). - Give up:
git merge --abort/git rebase --abort.
Diagnose: what each part of the command does
--name-onlylist file names only--diff-filter=Uonly Unmerged (conflicted) files
- Edit the files, remove the markers,
git switch -c <new-branch>detached HEADError codes & fixesKeep work done in detached HEADWhat it means
You checked out a commit or tag directly, not a branch. New commits belong to no branch.
Usual causes & fixes
- Already switched away? Find the commit in
git reflog.
Diagnose: what each part of the command does
switch -c <new-branch>create a branch at the current commit so the work is not lost
- Already switched away? Find the commit in
git rev-parse --show-toplevelnot a git repositoryError codes & fixes"fatal: not a git repository"What it means
The current folder is not inside a Git working tree.
Usual causes & fixes
cdinto the repo, orgit init/git clonefirst.- In CI/containers: "dubious ownership" →
git config --global --add safe.directory <path>.
Diagnose: what each part of the command does
rev-parse --show-toplevelprint the repo root, or fail if you are not inside a repo
terraform force-unlock <lock-id>state lockError codes & fixesTerraform "Error acquiring the state lock"DestructiveWhat it means
Another run holds the state lock, or a crashed/cancelled run left it behind.
Usual causes & fixes
- Make sure no other plan/apply is running first.
- Avoid by not cancelling apply jobs; use a CI concurrency group per workspace.
Diagnose: what each part of the command does
force-unlock <lock-id>remove the lock (ID is in the error message)
helm history <release> -n <namespace>another operation in progressError codes & fixesHelm "another operation (install/upgrade/rollback) is in progress"What it means
A previous Helm operation was interrupted and left the release in a pending state.
Usual causes & fixes
- Roll back to the last deployed revision:
helm rollback <release> <revision> -n <namespace>. - Use
--rollback-on-failure(Helm 4) /--atomic(Helm 3) and a timeout so this cleans up itself.
Diagnose: what each part of the command does
history <release>revisions; the last one is stuck in pending-install / pending-upgrade
- Roll back to the last deployed revision:
Shell basics: help, variables, pipes & chaining25
man <command>Linux & shellRead the manual for a commandWhat each part does
manmanual page; / to search, q to quit<command>e.g. man ls, man tar
<command> --helpLinux & shellQuick help for a commandwhich <command>; type <command>Linux & shellWhere is a command installed?What each part does
whichpath of the program that would runtypealso tells you if it is an alias, built-in or function
history | grep <word>Linux & shellSearch your command historyWhat each part does
historynumbered list of commands you ran| grep <word>only the ones containing <word>; re-run one with !<number>
Tip Faster: press Ctrl+R and start typing to search history interactively.
Linux & shell cheat sheet →sudo !!Linux & shellRe-run the last command with sudoWhat each part does
sudorun as root!!history expansion: the whole previous command
alias ll='ls -lh'Linux & shellCreate a shortcut commandWhat each part does
aliasdefine a short name for a commandll='ls -lh'typing ll now runs ls -lh (add it to ~/.bashrc to keep it)
echo "$HOME"Linux & shellPrint a variableWhat each part does
echoprint text"$HOME"value of the HOME variable; quotes keep spaces intact
export <NAME>=<value>Linux & shellSet a variable for this shell and its programsWhat each part does
exportmake the variable visible to programs you start from this shell<NAME>=<value>no spaces around =
env | grep <NAME>Linux & shellShow environment variablesWhat each part does
envall environment variables| grep <NAME>only matching ones
sudo <command>; sudo -iLinux & shellRun as root / open a root shellCautionWhat each part does
sudo <command>run one command as root (asks for your password)sudo -iinteractive root login shell; type exit to leave
Tab · Ctrl+C · Ctrl+R · Ctrl+L · Ctrl+DLinux & shellUseful keysWhat each part does
Tabcomplete file and command names (press twice to list options)Ctrl+Cstop the running commandCtrl+Rsearch command historyCtrl+Lclear the screen (same as clear)Ctrl+Dend input / log out of the shell
cmd1 | cmd2Linux & shellSend the output of one command into anotherWhat each part does
cmd1first command; its normal output (stdout) is captured|pipe: stdout of the left command becomes the input (stdin) of the right onecmd2second command, reads that input (e.g. grep, sort, head)
cmd > out.txt; cmd >> out.txtLinux & shellSave output to a file (overwrite / append)What each part does
>redirect stdout to a file, creating it or truncating it to empty first;run the next command after the first, whatever its result>>append stdout to the end of the file (creates it if missing)
cmd > out.log 2>&1Linux & shellCapture errors together with normal outputWhat each part does
> out.logstdout (file descriptor 1) goes to out.log2>&1make stderr (fd 2) point where stdout points. Order matters: it must come after > out.log
Tip Short bash form: cmd &> out.log
Linux & shell cheat sheet →make build && make deploy || echo "failed"Linux & shellRun the next command only if the previous one succeeded / failedWhat each part does
make buildfirst command&&run the next command only if the previous exited with code 0 (success)make deployruns only after a successful build||run the next command only if the previous exited non-zero (failure)echo "failed"fallback message
kill $(pgrep -f <name>)Linux & shellUse the output of a command as an argumentWhat each part does
killsend a signal (TERM by default) to process IDs$( … )command substitution: run the inner command and paste its output herepgrep -f <name>print PIDs whose full command line matches <name>
cat <list-file> | xargs -r -n 1 <cmd>Linux & shellPass input lines as arguments to another commandWhat each part does
cat <list-file>print the file (one item per line)|pipe into xargsxargsbuild and run command lines from its input-rdon't run the command at all if the input is empty (GNU xargs)-n 1one input item per command invocation<cmd>the command to run with each item appended
tmux new -A -s <name>Linux & shellStart or reattach a tmux sessionWhat each part does
tmux new -s <name>new named session that survives SSH disconnects-Aattach instead if it already exists
Tip Detach with Ctrl+B then D; list with tmux ls.
Linux & shell cheat sheet →<command> | jq '.items[] | {name: .metadata.name, phase: .status.phase}'Linux & shellPretty-print and filter JSONWhat each part does
| jq '...'JSON processor.items[]iterate over an array{name: ..., phase: ...}build a smaller object with just those fields
jq -r '.[] | select(.state=="running") | .name' <file>.jsonLinux & shellRaw values from JSON for scriptsWhat each part does
-rraw strings, no quotesselect(.state=="running")keep only matching items.nameprint one field
yq '.spec.replicas' <file>.yaml; yq -i '.spec.replicas = 3' <file>.yamlLinux & shellRead or edit YAMLWhat each part does
yq '.path'read a value (jq syntax for YAML)yq -i '...'edit the file in place
nohup <command> > <log> 2>&1 &Linux & shellKeep a command running after logoutWhat each part does
nohupignore the hangup signal sent when you log out> <log> 2>&1send output and errors to a log&run in the background; jobs and fg to manage it
timeout 30s <command>Linux & shellStop a command that runs too longWhat each part does
timeout 30skill the command after 30 seconds; exit code 124 if it timed out
cat <list> | xargs -P 8 -I{} <command> {}Linux & shellRun commands in parallelWhat each part does
xargs -P 8up to 8 at a time-I{}replace {} in the command with each input line
until <command>; do echo retrying; sleep 5; doneLinux & shellRetry a command until it succeedsWhat each part does
until <command>loop while the command failssleep 5wait between attempts
Everyday basics: Docker, Kubernetes, Git51
docker version; docker infoDockerIs Docker installed and running?What each part does
docker versionclient and server (daemon) versions; an error on Server means the daemon is not runningdocker infosystem-wide details: containers, images, storage driver, cgroup driver
docker run --rm hello-worldDockerTest that everything worksWhat each part does
docker runcreate and start a container (pulls the image if missing)--rmremove the container when it exitshello-worldtiny test image that prints a greeting
docker imagesDockerList local imagesWhat each part does
docker imagesalias of docker image ls: repository, tag, image ID, size
docker pull <image>:<tag>DockerDownload an imageWhat each part does
docker pulldownload from a registry (Docker Hub by default)<image>:<tag>e.g. nginx:1.27; without a tag it means :latest
docker ps; docker ps -aDockerList running / all containersdocker start <container>; docker stop <container>; docker restart <container>DockerStart, stop, restart a containerWhat each part does
startstart a stopped container (keeps its data and settings)stopgraceful stop: SIGTERM, then SIGKILL after 10s (-t to change)restartstop then start
docker rm <container>DockerRemove a containerCautionWhat each part does
docker rmdelete a stopped container; add -f to stop and delete a running one
docker rmi <image>:<tag>DockerRemove an imageCautionWhat each part does
docker rmidelete a local image; -f forces it even if tagged elsewhere
docker rename <old-name> <new-name>DockerRename a containerdocker port <container>DockerWhich host port maps to the container?docker login <registry>; docker logout <registry>DockerLog in / out of a registryWhat each part does
docker loginstore credentials (Docker Hub if no registry is given)docker logoutremove them
kubectl versionKubernetesClient and cluster versionWhat each part does
kubectl versionclient and server versions; add --client for the client only (no cluster needed)
kubectl cluster-infoKubernetesIs the cluster reachable?What each part does
cluster-infoaddresses of the control plane and core services
kubectl get nodes -o wideKubernetesList nodesWhat each part does
get nodescluster nodes and whether they are Ready-o wideadd internal/external IP, OS, kernel, container runtime
kubectl get nsKubernetesList namespaceskubectl create namespace <namespace>KubernetesCreate a namespacekubectl get all -n <namespace>KubernetesEverything in a namespaceWhat each part does
get allpods, services, deployments, replicasets, statefulsets, jobs… (not configmaps/secrets/ingress)-n <namespace>--namespace: which namespace
kubectl get deploy,svc,ing -n <namespace>KubernetesDeployments, services and ingresses at onceWhat each part does
deploy,svc,ingcomma-separated resource types (short names)
kubectl get configmap,secret -n <namespace>KubernetesConfigMaps and SecretsWhat each part does
configmap,secretconfig objects (secret values are not shown here)
kubectl get pods -wKubernetesWatch pods change livekubectl get pod <pod> -o yamlKubernetesFull YAML of a live objectkubectl apply -f <file-or-dir>KubernetesCreate / update from a fileWhat each part does
applycreate or update to match the manifest-f--filename: a file, a folder or a URL (add -R for sub-folders)
kubectl delete -f <file-or-dir>KubernetesDelete what a file definesDestructivekubectl edit deploy/<deployment>KubernetesEdit a live object in your editorCautionWhat each part does
editopens the object in $EDITOR (KUBE_EDITOR); saving applies it
kubectl label pod <pod> <key>=<value> --overwriteKubernetesAdd or change a labelWhat each part does
labelset labels on objects<key>=<value>the label; <key>- (trailing dash) removes it--overwriteallow replacing an existing value
kubectl expose deployment <deployment> --port=80 --target-port=8080 --type=ClusterIPKubernetesExpose a deployment as a serviceWhat each part does
exposecreate a Service for a workload--port=80port the Service listens on--target-port=8080container port the traffic goes to--type=ClusterIPClusterIP (default, in-cluster), NodePort or LoadBalancer
kubectl run tmp --rm -it --restart=Never --image=busybox:1.36 -- shKubernetesThrow-away debug pod with a shellWhat each part does
run tmpcreate a pod named tmp--rmdelete it when you exit-itinteractive terminal--restart=Nevera plain pod, not managed by anything--image=busybox:1.36small image with basic tools (nslookup, wget)-- shcommand to run
kubectl get secret <secret> -o jsonpath='{.data.<key>}' | base64 -dKubernetesRead one value from a SecretCautionWhat each part does
-o jsonpath=…print just that field{.data.<key>}the base64-encoded value of <key>| base64 -ddecode it to plain text
Tip Prints a secret to your terminal.
Kubernetes cheat sheet →git config --global user.name "<name>"; git config --global user.email "<email>"GitSet your name and email (once per machine)What each part does
git configread/write Git settings--globalfor your user (~/.gitconfig), all reposuser.name / user.emailrecorded as the author of your commits
Tip Git 2.46+ also has: git config set --global user.name "<name>". Check with git config list --show-origin.
Git cheat sheet →git init -b mainGitStart a new repoWhat each part does
initcreate a .git folder here-b main--initial-branch: name the first branch main
git clone <url>GitCopy a remote repoWhat each part does
clone <url>download the repo with full history into a new folder
git clone --depth 1 <url>GitShallow clone (fast, latest commit only)git statusGitWhat changed?git add <file>; git add -AGitStage one file / everythingWhat each part does
add <file>stage that file for the next commitadd -A--all: stage every change in the repo, including deletions (git add . = only under the current folder)
git add -pGitStage only parts of a filegit commit -m "<message>"GitCommit staged changesWhat each part does
commitrecord the staged changes-m "<message>"commit message (without -m an editor opens)
git commit -am "<message>"GitStage tracked files and commit in one stepWhat each part does
-a--all: auto-stage modified and deleted tracked files (NOT new files)-mmessage
git commit --amend --no-editGitFix the last commit (not pushed yet)CautionWhat each part does
--amendreplace the last commit with one that includes what is staged now--no-editkeep the same message
git log --oneline -n 10GitRecent historygit diff; git diff --stagedGitSee the changesWhat each part does
git diffchanges not staged yet--stagedwhat is staged (alias --cached)
git show <commit>GitShow one commitgit branch -aGitList branchesWhat each part does
-a--all: local and remote-tracking branches; * marks the current one
git checkout -b <branch>GitCreate and switch to a branchgit branch -d <branch>; git branch -D <branch>GitDelete a branchCautiongit merge --no-ff <branch>GitMerge a branch into the current oneWhat each part does
merge <branch>bring <branch>'s commits into the current branch--no-ffalways create a merge commit, even when a fast-forward is possible
Tip Conflict? Fix the files, git add them, git commit, or give up with git merge --abort.
Git cheat sheet →git remote -vGitWhich remotes are set up?git remote add origin <url>GitAdd a remotegit pullGitGet the latest from the remoteWhat each part does
pullfetch + merge the upstream branch (git pull --rebase to rebase instead)
git pushGitUpload your commitsWhat each part does
pushsend commits to the upstream branch (first time: git push -u origin <branch>)
git rm --cached <file>GitStop tracking a file but keep it on diskWhat each part does
rmremove from Git--cachedonly from the index; the file stays (then add it to .gitignore)
git mv <old> <new>GitRename a tracked file
Permissions & ownership (chmod, chown, ACL)31
ls -l <file>Linux & shellRead a permission stringWhat it means
On a directory: r = list names, w = create/delete entries, x = enter it / reach things inside.
What each part does
-rwxr-xr-xexample output; 1st char is the type: - file, d directory, l symlinkrwxchars 2-4, owner (user): r read, w write, x executer-xchars 5-7, group: - means "not allowed"r-xchars 8-10, others (everyone else)s / ts in an x slot = setuid/setgid, t in the last slot = sticky (capital S/T = bit set but no x)+a trailing + means extra ACL entries exist (see getfacl)
stat -c '%a %A %U:%G %n' <file>Linux & shellSee permissions as numbersWhat each part does
stat -cprint chosen fields%apermissions in octal, e.g. 755%Athe same as letters, e.g. -rwxr-xr-x%U:%Gowner user and group%nfile name
chmod 755 <file-or-dir>Linux & shellOctal modes explained: 755What each part does
chmodchange mode (permissions)7owner = 4 read + 2 write + 1 execute = rwx5group = 4 read + 1 execute = r-x5others = r-x
Tip Typical for folders, scripts and binaries.
Linux & shell cheat sheet →chmod 644 <file>Linux & shellRegular files: owner writes, everyone readsWhat each part does
6owner rw- (4+2)4group r--4others r--
Tip Typical for config files, web content, documents.
Linux & shell cheat sheet →chmod 600 <file>Linux & shellPrivate file: only the ownerWhat each part does
6owner rw-0group: nothing0others: nothing
Tip Use for secrets: .env files, private keys, kubeconfig, credentials.
Linux & shell cheat sheet →chmod 700 <dir>Linux & shellPrivate folder / script: only the ownerchmod 750 <dir>; chmod 640 <file>Linux & shellShared with the group, hidden from othersWhat each part does
750dir: owner rwx, group r-x (can enter and read), others none640file: owner rw-, group r--, others none
chmod 400 <file>Linux & shellRead-only for the ownerWhat each part does
4owner r-- only00nobody else
Tip AWS .pem key files are expected to be 400 or 600.
Linux & shell cheat sheet →chmod 777 <path>Linux & shell777: everyone can do everything (avoid)DestructiveWhat each part does
7 7 7rwx for owner, group and ALL other users
Tip Any user or compromised process can change or replace the file, or delete files in the folder. Fix ownership or group instead (chown / chgrp + 775 or 770).
Linux & shell cheat sheet →chmod +x <script>.sh && ./<script>.shLinux & shellMake a script executable and run itWhat each part does
+xadd execute (no who-letter = for all, minus the umask bits)&&then./<script>.shrun it from the current folder (. is not on PATH)
chmod u+x,g-w,o-rwx <file>Linux & shellSymbolic: add or remove for owner/group/othersWhat each part does
u+xu = owner (user): add execute,separate clausesg-wg = group: remove writeo-rwxo = others: remove everything
Tip Who: u, g, o, a (all). Operator: + add, - remove, = set exactly. Perms: r w x X s t.
Linux & shell cheat sheet →chmod u=rwx,go=rx <path>Linux & shellSymbolic: set exact permissionsWhat each part does
u=rwxowner gets exactly rwxgo=rxgroup and others get exactly r-x (same as 755)
chmod a+r <file>Linux & shellGive everyone read accesschmod -R u+rwX,go+rX,go-w <dir>Linux & shellRecursive, the safe way (capital X)What each part does
-R--recursive: the folder and everything insideu+rwXowner: read, write, and execute only for folders / files already executablego+rXgroup/others: read, and enter foldersgo-wgroup/others: no write
Tip X (capital) avoids making every plain file executable, which chmod -R 755 would do.
Linux & shell cheat sheet →find <dir> -type d -exec chmod 755 {} + && find <dir> -type f -exec chmod 644 {} +Linux & shellFolders 755, files 644 (fix a messy tree)CautionWhat each part does
find <dir> -type devery directory under <dir>-exec chmod 755 {} +run chmod on them in batches ({} = the found names)&&then-type f … chmod 644every regular file gets 644
Tip Re-add +x afterwards to scripts that need it.
Linux & shell cheat sheet →chmod --reference=<source-file> <file>Linux & shellCopy permissions from another fileWhat each part does
--reference=<source-file>use that file's mode instead of typing one
sudo chown <user> <path>Linux & shellChange the ownersudo chown -R <user>:<group> <path>Linux & shellChange owner and group, recursivelyWhat each part does
-Rrecursive<user>:<group>both at once (no spaces). <user>: alone = also set the user's login group
sudo chgrp -R <group> <path>Linux & shellChange only the groupsudo chown -R --from=<old-user> <new-user> <dir>Linux & shellRe-own only files that belong to someone elseWhat each part does
--from=<old-user>change only files currently owned by <old-user><new-user>new owner
sudo chgrp <group> <dir> && sudo chmod 2775 <dir>Linux & shellShared team folder: new files keep the folder groupWhat each part does
chgrp <group> <dir>folder belongs to the team group2setgid bit: new files/folders inside inherit the folder's group775owner and group rwx, others r-x
Tip Symbolic form: chmod g+s <dir>.
Linux & shell cheat sheet →sudo chmod 1777 <dir>Linux & shellSticky folder: users can only delete their own filesWhat each part does
1sticky bit: only the file owner (or dir owner/root) can delete or rename entries777everyone can create files
Tip This is how /tmp is set up (drwxrwxrwt). Symbolic: chmod +t <dir>.
Linux & shell cheat sheet →sudo find / -xdev -type f -perm /4000 2>/dev/nullLinux & shellFind setuid programs (security audit)What each part does
-xdevstay on one filesystem-type ffiles only-perm /4000any file with the setuid bit (runs as its owner, often root)2>/dev/nullhide "Permission denied" noise
find <dir> -type f -perm -o+wLinux & shellFind world-writable filesWhat each part does
-perm -o+w"-" = all listed bits must be set: others have write
umask; umask 027Linux & shellDefault permissions for new files (umask)What each part does
umaskshow the current mask (usually 0022)umask 027set it for this shell: bits in the mask are REMOVED from new files
Tip New files start from 666, folders from 777. 022 → files 644, dirs 755. 027 → 640 / 750. 077 → 600 / 700. Put it in ~/.bashrc or the service unit (UMask=) to keep it.
Linux & shell cheat sheet →setfacl -m u:<user>:rwx <path>Linux & shellGive one extra user access (ACL)What each part does
setfaclset file access control lists-m--modify: add or change an entryu:<user>:rwxentry: u = user, then the name, then permissions (g:<group>:rx for a group)
setfacl -R -m u:<user>:rwX <dir> && setfacl -d -m u:<user>:rwX <dir>Linux & shellACL for everything inside, and for future filesWhat each part does
-Rapply to existing files recursively-d--default: entries that NEW files and folders inside will inheritrwXX = execute only on folders/executables
getfacl <path>Linux & shellShow ACLsWhat each part does
getfaclowner, group, and every ACL entry with its effective rights (mask applies)
setfacl -x u:<user> <path>; setfacl -b <path>Linux & shellRemove ACL entriesWhat each part does
-x u:<user>remove that user's entry (no permissions in the spec)-b--remove-all: drop every extra entry, keep owner/group/others
chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys ~/.ssh/id_ed25519Linux & shellSSH files: fix permissions so sshd accepts themWhat each part does
700 ~/.sshonly you can enter or list the folder600 authorized_keysonly you can read/write the list of allowed keys600 id_ed25519private key readable only by you (public .pub can be 644)
Tip With StrictModes (default yes) sshd refuses keys if these are group/world-writable.
Linux & shell cheat sheet →namei -l <path>Linux & shellWhy is access denied? Check every folder on the pathWhat each part does
namei -llist owner, group and mode of each component: missing x on any parent blocks access
Users & groups6
whoami; idLinux & shellWho am I?What each part does
whoamiyour user nameidyour user ID, primary group and all groups
groups <user>Linux & shellWhich groups is a user in?su - <user>Linux & shellSwitch to another userWhat each part does
susubstitute user-start a full login shell (their home folder and environment)
sudo useradd -m -s /bin/bash <user>Linux & shellCreate a user with a home folder and bashWhat each part does
useraddcreate a user account-m--create-home: create /home/<user> with the skeleton files-s /bin/bash--shell: login shell
sudo usermod -aG <group> <user>Linux & shellAdd a user to a group (keep other groups)What each part does
usermodmodify a user-a--append: add to the group (only valid with -G)-G <group>supplementary group(s). Without -a the user is REMOVED from groups not listed
Tip Typical: sudo usermod -aG docker $USER, then log out and in again.
Linux & shell cheat sheet →sudo passwd <user>Linux & shellSet or change a passwordWhat each part does
passwdchange the password (your own if no user given, no sudo needed)
Install packages36
sudo apt update && sudo apt upgrade -yLinux & shellRefresh package lists and upgrade (Debian/Ubuntu)What each part does
apt updatedownload the latest package lists (installs nothing)&&only if that workedapt upgradeinstall newer versions of installed packages-yanswer yes to the prompt
sudo apt install -y <package>Linux & shellInstall a packageWhat each part does
apt installinstall a package and its dependencies-yno confirmation prompt
sudo apt remove <package>Linux & shellRemove a packageCautionWhat each part does
apt removeuninstall (keeps config files; apt purge removes those too)
apt search <word>Linux & shellFind a packageapt list --installed | grep <package>Linux & shellIs it installed?What each part does
apt list --installedevery installed package| grep <package>filter to the one you want
sudo dnf install -y <package>Linux & shellInstall on RHEL / Fedora / Amazon LinuxWhat each part does
dnf installinstall with the dnf package manager (yum on older systems)-yno prompt
apk add --no-cache <package>Linux & shellInstall on Alpine (common in containers)What each part does
apk addAlpine's package manager--no-cachedon't keep the package index: smaller images
hostnamectlLinux & shellOS, version and kernel in one viewWhat each part does
hostnamectlhostname, operating system and version, kernel, architecture, virtualization (systemd systems)
<program> --versionLinux & shellVersion of any programWhat each part does
<program> --versionmost tools print their version; some use -v or -V (nginx -v, java -version, python3 -V)
dpkg -S "$(command -v <program>)"Linux & shellWhere is a command, and which package installed it? (Debian / Ubuntu)What each part does
command -v <program>full path of the program the shell would rundpkg -S <path>the package that owns that file
rpm -qf "$(command -v <program>)"Linux & shellWhich package installed a command? (RHEL / Fedora / Amazon Linux)What each part does
command -v <program>full path of the programrpm -qf <path>package (name-version-release) that owns that file
dpkg-query -W -f='${Package} ${Version} ${Status}\n' <package>Linux & shellInstalled version of one package (Debian / Ubuntu)What each part does
dpkg-query -Wshow installed package info-f='${Package} ${Version} ${Status}\n'output format: name, version, install status<package>package name; wildcards work, e.g. 'openssl*'
apt-cache policy <package>Linux & shellInstalled vs available version (Debian / Ubuntu)What each part does
apt-cache policyInstalled: version now, Candidate: what apt install/upgrade would get, plus the version table per repo<package>package name
apt list -a <package>Linux & shellAll versions the repos offer (Debian / Ubuntu)What each part does
apt list -aevery available version, marked [installed] / [upgradable]
sudo apt update && apt list --upgradableLinux & shellPackages with updates available (Debian / Ubuntu)What each part does
apt updaterefresh package lists first, or the answer is staleapt list --upgradableinstalled packages with a newer version: name, new version, [upgradable from: old]
dpkg-query -W -f='${Package}\t${Version}\n' | sortLinux & shellEvery installed package with its version (Debian / Ubuntu)What each part does
dpkg-query -W -f='...'name TAB version for every installed package| sortalphabetical; redirect to a file to diff two servers
rpm -q <package>Linux & shellInstalled version of one package (RHEL / Fedora / Amazon Linux / SUSE)What each part does
rpm -q <package>name-version-release.arch, or 'package ... is not installed'
rpm -qi <package>Linux & shellDetails of an installed package (RHEL family)What each part does
rpm -qiversion, release, install date, vendor, build date, summary
dnf list --showduplicates <package>Linux & shellInstalled and available versions (RHEL / Fedora)What each part does
dnf listInstalled Packages section and Available Packages section--showduplicatesevery available version, not just the newest (to pick one to install or downgrade)
dnf check-updateLinux & shellPackages with updates available (RHEL / Fedora)What each part does
dnf check-updatelist pending updates; exit code 100 means updates exist, 0 means none (yum check-update on older systems)
dnf updateinfo list --securityLinux & shellPending security updates only (RHEL / Fedora)What each part does
dnf updateinfo listadvisories for available updates--securityonly security fixes, with severity and advisory ID
rpm -qa --last | head -30Linux & shellEvery installed package, newest installs first (RHEL family)What each part does
rpm -qaall installed packages--lastsorted by install/update time, newest first, with the date| head -30the 30 most recent
dnf history; dnf history info <id>Linux & shellWhat changed recently? (RHEL / Fedora)What each part does
dnf historyevery install/upgrade/remove transaction with date and userdnf history info <id>exact packages and versions in that transaction; dnf history undo <id> reverts it
grep -E ' (install|upgrade) ' /var/log/dpkg.logLinux & shellWhat was installed or upgraded recently? (Debian / Ubuntu)What each part does
grep -E ' (install|upgrade) 'only install and upgrade lines (date, package, old and new version)/var/log/dpkg.logdpkg's log; older months are in dpkg.log.1 and .gz files (zgrep)
apk info -v <package>; apk policy <package>Linux & shellInstalled version of one package (Alpine)What each part does
apk info -v <package>installed name-versionapk policy <package>installed and available versions per repository
apk update && apk version -l '<'Linux & shellPackages with updates available (Alpine)What each part does
apk updaterefresh the indexapk version -l '<'only packages whose installed version is older than the repo's
zypper info <package>Linux & shellInstalled version of one package (SUSE)What each part does
zypper infoversion, repository, installed status of a package
snap list; flatpak list --columns=application,versionLinux & shellSnap and Flatpak packages with versionsWhat each part does
snap listsnaps: name, version, revision, channelflatpak list --columns=...flatpak apps and their versions
python3 -m pip list; python3 -m pip show <package>Linux & shellPython packages and versionsWhat each part does
python3 -m pip listevery package in this Python environment with its version (add --outdated for updates)pip show <package>version, location and dependencies of one package
node --version; npm ls -g --depth=0Linux & shellGlobal Node.js packages and versionsWhat each part does
node --versionNode.js versionnpm ls -g --depth=0globally installed npm packages, top level only
ldd --version | head -1; openssl version -a | head -2Linux & shellCore library versions (glibc, OpenSSL)What each part does
ldd --versionthe C library (glibc) version; matters for binary compatibility and CVEsopenssl version -aOpenSSL version and build date
sudo apt install <package>=<version>Linux & shellInstall a specific version (Debian / Ubuntu)CautionWhat each part does
<package>=<version>exact version from apt list -a; add --allow-downgrades to go back
sudo dnf install <package>-<version>Linux & shellInstall a specific version (RHEL / Fedora)CautionWhat each part does
<package>-<version>exact version from dnf list --showduplicates; dnf downgrade to go back
sudo apt-mark hold <package>; sudo dnf versionlock add <package>Linux & shellStop a package from being upgradedWhat each part does
apt-mark holdDebian / Ubuntu: keep the current version (apt-mark unhold to release)dnf versionlock addRHEL / Fedora: same idea (needs the versionlock plugin)
dnf provides '*/<file>'; apt-file search <file>Linux & shellWhich package provides a file you don't have?What each part does
dnf provides '*/<file>'RHEL family: packages containing that fileapt-file search <file>Debian / Ubuntu (install apt-file and run apt-file update first)
ansible all -i <inventory> -m shell -a "rpm -q <package> 2>/dev/null || dpkg-query -W <package>"Linux & shellCheck a package version across many serversWhat each part does
ansible all -i <inventory>every host in the inventory-m shell -a "..."run the command on each onerpm -q <package> || dpkg-query -W <package>works on both RHEL- and Debian-family hosts
Tip Without Ansible: for h in <host1> <host2>; do echo "$h: $(ssh $h 'rpm -q <package> 2>/dev/null || dpkg-query -W <package>')"; done
Linux & shell cheat sheet →
System info, processes & disk63
uname -aLinux & shellKernel and architectureWhat each part does
unamesystem information-aall: kernel name, hostname, release, version, architecture
cat /etc/os-releaseLinux & shellWhich Linux distribution and version?What each part does
/etc/os-releaseNAME, VERSION_ID, ID of the distro (ubuntu, debian, rhel…)
hostname; hostname -ILinux & shellHost name and IP addressesWhat each part does
hostnamethe machine name-Iall IP addresses of the host
uptimeLinux & shellHow long has it been running? Load?What each part does
uptimetime since boot, logged-in users, load average over 1/5/15 minutes
date; timedatectlLinux & shellDate, time and timezoneWhat each part does
datecurrent date and timetimedatectltimezone and whether NTP sync is active
nproc; lscpuLinux & shellCPU cores and modelWhat each part does
nprocnumber of CPUs availablelscpuCPU model, cores, threads, architecture
lsblkLinux & shellDisks and partitionsWhat each part does
lsblkblock devices as a tree: disks, partitions, sizes, mount points
findmntLinux & shellWhat is mounted whereWhat each part does
findmntmounted filesystems as a tree (cleaner than mount)
sudo reboot; sudo shutdown -h nowLinux & shellReboot / shut downDestructiveWhat each part does
rebootrestart the machineshutdown -h now-h = halt/power off, now = immediately (or +10 for 10 minutes)
ps aux | grep <name>Linux & shellFind a process by nameWhat each part does
pssnapshot of current processesauxBSD-style options (no dash): a = all users, u = user-oriented columns (USER, %CPU, %MEM…), x = include processes without a terminal|pipe the process list into grepgrep <name>keep only lines containing <name>
Tip The grep line itself matches too. Use grep "[n]ginx" (brackets on one letter) or pgrep -a <name>.
Linux & shell cheat sheet →ps aux --sort=-%mem | headLinux & shellTop 10 processes by memoryWhat each part does
ps auxall processes, user-oriented columns--sort=-%memsort by memory share; the leading "-" means descending| headkeep the first 10 lines (header + top 9)
ps -eo pid,user,%cpu,%mem,comm --sort=-%cpu | head -n 15Linux & shellCustom columns sorted by CPUWhat each part does
-eselect every process-o pid,user,%cpu,%mem,commchoose the output columns: PID, owner, CPU %, memory %, executable name--sort=-%cpuhighest CPU firsthead -n 15first 15 lines
top -b -n 1 | head -n 20Linux & shellOne-shot top output (for logs or scripts)What each part does
toplive process viewer-bbatch mode: plain text, no interactive screen (works in pipes)-n 1stop after one refreshhead -n 20summary lines plus the top processes
kill <pid>; sleep 5; kill -9 <pid>Linux & shellStop a process gracefully, then forcefullyCautionWhat each part does
kill <pid>send SIGTERM (15): asks the process to exit and clean upsleep 5give it time to shut downkill -9 <pid>send SIGKILL: cannot be caught, ends it immediately (no cleanup)
free -hLinux & shellMemory usage in human unitsWhat each part does
freeshow RAM and swap usage-hhuman-readable units (Mi, Gi). Look at the "available" column, not "free"
df -hT; df -iLinux & shellDisk space per filesystem (and inodes)What each part does
dfreport filesystem usage-hhuman-readable sizes-Tshow the filesystem typedf -iinode usage instead of space. A disk can be "full" on inodes
du -sh * | sort -rh | headLinux & shellBiggest items in the current folderWhat each part does
duestimate file/directory space-sone total per argument-hhuman-readable sizes*every entry in the current directory (shell glob)sort -rhsort human sizes (-h knows 2K < 1G), largest first (-r)headtop 10
du -xh -d 1 <dir> | sort -rh | head -n 15Linux & shellFolder sizes one level deep, same filesystemWhat each part does
-xdon't cross into other mounted filesystems-hhuman-readable-d 1only show totals one level below <dir> (same as --max-depth=1)sort -rh | head -n 15largest 15
crontab -l; crontab -eLinux & shellList and edit your cron jobsWhat each part does
crontab -lshow your user's cron jobs (sudo crontab -l -u <user> for others)crontab -eedit them in $EDITOR
*/5 * * * * /usr/local/bin/<script> >> /var/log/<script>.log 2>&1Linux & shellCron line formatWhat each part does
*/5 * * * *minute hour day-of-month month day-of-week: here every 5 minutes/usr/local/bin/<script>use full paths: cron has a minimal PATH>> <log> 2>&1append output and errors to a log, otherwise they are mailed or lost
ls /etc/cron.d /etc/cron.daily /etc/cron.hourly; cat /etc/crontabLinux & shellSystem-wide cron jobsWhat each part does
/etc/cron.djob files from packages and admins (with a user field)/etc/cron.daily, hourly...scripts run by run-parts at those intervals
journalctl -u cron -u crond --since todayLinux & shellDid cron run my job?What each part does
journalctl -u cron -u crondcron daemon logs (cron on Debian, crond on RHEL); or grep CRON /var/log/syslog--since todayonly today
systemctl list-timers --allLinux & shellList systemd timers and when they run nextWhat each part does
list-timersevery timer: next run, last run, the unit it starts--allinclude inactive timers
echo '<command>' | at 02:00Linux & shellRun a command once at a later timeWhat each part does
at 02:00run once at 2 AM (also: at now + 30 minutes); atq lists, atrm removes
lsblk -fLinux & shellDisks, partitions and filesystemsWhat each part does
lsblkblock devices as a tree: disks, partitions, LVM volumes-fadd filesystem type, label, UUID and mount point
sudo mount <device> <mount-point>Linux & shellMount a filesystemWhat each part does
mount <device>e.g. /dev/sdb1 or /dev/mapper/vg-data<mount-point>existing empty directory, e.g. /mnt/data
sudo findmnt --verify && sudo mount -aLinux & shellTest /etc/fstab before rebootingWhat each part does
findmnt --verifycheck fstab syntax, devices and filesystem typesmount -amount everything in fstab now; a typo here would otherwise stop the next boot
sudo umount <mount-point> || sudo lsof +f -- <mount-point>Linux & shellUnmount, and find what keeps it busyWhat each part does
umountunmountlsof +f -- <mount-point>processes with files open there (target is busy)
sudo mkfs.ext4 -L <label> <device>Linux & shellCreate a filesystem on a new diskDestructiveWhat each part does
mkfs.ext4format as ext4 (mkfs.xfs for XFS): erases the device-L <label>filesystem label
sudo growpart <disk> <partition-number> && sudo resize2fs <partition>Linux & shellGrow a partition and filesystem after enlarging a cloud diskCautionWhat each part does
growpart /dev/xvda 1extend partition 1 to fill the disk (cloud-guest-utils)resize2fs <partition>grow an ext4 filesystem; for XFS: xfs_growfs <mount-point>
sudo pvs; sudo vgs; sudo lvsLinux & shellLVM overviewWhat each part does
pvsphysical volumes (disks in LVM)vgsvolume groups and their free spacelvslogical volumes and sizes
sudo lvextend -r -L +<size>G /dev/<vg>/<lv>Linux & shellExtend a logical volume and its filesystemCautionWhat each part does
lvextendgrow a logical volume-ralso resize the filesystem in one step-L +<size>Gadd this much (or -l +100%FREE for all free space)
swapon --show; sudo fallocate -l 2G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfileLinux & shellShow swap, and add a swap fileWhat each part does
swapon --showactive swap devices and usagefallocate -l 2G /swapfilecreate a 2 GB filechmod 600only root may read itmkswap / swaponformat it as swap and enable it (add to fstab to keep it)
df -iLinux & shellOut of inodes? (disk full with free space left)What each part does
df -iinode usage per filesystem; 100% means no new files even if space is free (millions of tiny files)
sudo dmesg -T | tail -50Linux & shellKernel messages with readable timesWhat each part does
dmesgkernel ring buffer: hardware errors, OOM killer, disk and network driver messages-Thuman-readable timestamps| tail -50the latest 50 lines
sudo dmesg -T | grep -i -E 'killed process|out of memory'Linux & shellDid the OOM killer kill something?What each part does
grep -i -E '...'lines where the kernel killed a process to free memory, with its name and memory use
lscpu; lspci; sudo dmidecode -t systemLinux & shellHardware overviewWhat each part does
lscpuCPU model, cores, threads, virtualizationlspciPCI devices: NICs, GPUs, storage controllersdmidecode -t systemvendor, model and serial number
sysctl <key>; sudo sysctl -w <key>=<value>Linux & shellRead and change kernel parametersCautionWhat each part does
sysctl <key>e.g. vm.swappiness, net.ipv4.ip_forward, fs.file-maxsysctl -w <key>=<value>change it now; put it in /etc/sysctl.d/*.conf to keep it after reboot
ulimit -n; cat /proc/<pid>/limitsLinux & shellOpen-file and process limitsWhat each part does
ulimit -nmax open files for this shell (Too many open files means you hit it)/proc/<pid>/limitsthe actual limits of a running process (systemd services set LimitNOFILE)
lsmod | grep <module>; sudo modprobe <module>Linux & shellKernel modulesWhat each part does
lsmodloaded modulesmodprobe <module>load a module with its dependencies (e.g. br_netfilter for Kubernetes)
timedatectlLinux & shellTime, timezone and NTP syncWhat each part does
timedatectllocal time, UTC, timezone and whether the clock is NTP-synchronized (clock skew breaks TLS and tokens)
uptimeLinux & shellUptime and load averageWhat each part does
uptimehow long since boot, users, and 1/5/15-minute load averages (compare with CPU count)
vmstat 1 5Linux & shellCPU, memory, swap and I/O wait every secondWhat each part does
vmstatr (run queue), free memory, si/so (swapping), wa (I/O wait), us/sy/id CPU1 5every 1 second, 5 times (the first line is the average since boot)
iostat -xz 1Linux & shellDisk I/O per deviceWhat each part does
iostatdisk statistics (sysstat package)-xextended: %util, await (latency), r/s, w/s-zhide idle devices1refresh every second
mpstat -P ALL 1Linux & shellCPU usage per coreWhat each part does
mpstatCPU statistics (sysstat)-P ALLevery core, to spot one core at 100%1every second
pidstat -u -r -d 1Linux & shellCPU, memory and I/O per process over timeWhat each part does
pidstatper-process statistics (sysstat)-u -r -dCPU, memory (faults, RSS) and disk I/O1every second
sudo iotop -oPaLinux & shellWhich processes do the most disk I/O?What each part does
iotoptop for disk I/O-oonly processes actually doing I/O-Pper process, not per thread-aaccumulated totals
ps -eo pid,user,%mem,rss,cmd --sort=-rss | head -15Linux & shellTop memory usersWhat each part does
ps -eo ...pick columns: PID, user, % of RAM, resident memory in KB, command--sort=-rssbiggest memory first| head -15top 14 plus the header
sudo strace -f -tt -p <pid> -e trace=network,fileLinux & shellTrace what a process is doing (system calls)What each part does
strace -p <pid>attach to a running process-ffollow its threads and children-tttimestamps with microseconds-e trace=network,fileonly network and file calls (drop it to see everything)
Tip Slows the process down a lot; use briefly in production.
Linux & shell cheat sheet →sudo perf topLinux & shellLive CPU profile of the whole systemWhat each part does
perf topfunctions using the most CPU right now, across kernel and user space
sar -n DEV 1Linux & shellNetwork traffic per interfaceWhat each part does
sar -n DEVpackets and KB per second per interface (sysstat)1every second; sar without a count reads history if sysstat collection is enabled
watch -n 2 -d '<command>'Linux & shellRe-run a command every few secondsWhat each part does
watchrun the command repeatedly, full-screen-n 2every 2 seconds-dhighlight what changed
kubectl cordon <node>KubernetesStop new pods landing on a nodeWhat each part does
cordonmark unschedulable; running pods stay (drain to evict them, uncordon to undo)
kubectl taint nodes <node> <key>=<value>:NoSchedule; kubectl taint nodes <node> <key>:NoSchedule-KubernetesTaint a node / remove a taintWhat each part does
<key>=<value>:NoScheduleonly pods tolerating this taint can schedule here (NoExecute also evicts)<key>:NoSchedule-trailing minus removes it
kubectl label node <node> <key>=<value>KubernetesLabel a nodeWhat each part does
label nodeused by nodeSelector / affinity, e.g. disktype=ssd
kubectl get nodes --show-labels; kubectl describe node <node> | grep -A3 TaintsKubernetesNode labels and taintsWhat each part does
--show-labelsall labels (zone, instance type, OS, arch)grep -A3 Taintstaints on the node
kubectl describe node <node> | grep -A8 'Allocated resources'KubernetesHow full is a node? (requests vs capacity)What each part does
Allocated resourcessum of CPU/memory requests and limits vs allocatable: why pods are Pending even if usage is low
kubectl auth can-i <verb> <resource> -n <namespace> --as=<user-or-sa>KubernetesCan I (or someone) do this?What each part does
auth can-iyes/no for an action, e.g. can-i delete pods--as=<user-or-sa>impersonate, e.g. system:serviceaccount:<ns>:<sa>
kubectl auth can-i --list -n <namespace>KubernetesEverything I am allowed to doWhat each part does
--listall verbs per resource for the current user in that namespace
kubectl auth whoamiKubernetesWho am I logged in as?What each part does
auth whoamiuser name and groups the API server sees for your credentials
kubectl create token <serviceaccount> -n <namespace> --duration=1hKubernetesCreate a short-lived token for a service accountWhat each part does
create tokenrequest a bound token (no long-lived secret)--duration=1hlifetime
kubectl get csr; kubectl certificate approve <csr>KubernetesApprove a certificate signing requestCautionWhat each part does
get csrpending node / user certificate requestscertificate approvesign it
kubectl versionKubernetesClient and server versionsWhat each part does
kubectl versionclient and API server versions; keep kubectl within one minor version of the server
Network & SSH40
ping -c 4 <host>Linux & shellIs a host reachable?What each part does
pingsend ICMP echo requests-c 4stop after 4 packets (otherwise it runs until Ctrl+C)
ssh <user>@<host>Linux & shellLog in to a serverWhat each part does
sshsecure shell<user>@<host>remote user name and host name or IP
ssh -p <port> -i <key-file> <user>@<host>Linux & shellSSH with a port and a key fileWhat each part does
-p <port>remote port (default 22)-i <key-file>private key to use
ssh <user>@<host> "<command>"Linux & shellRun one command remotelyWhat each part does
"<command>"runs on the server, output comes back to you
ssh-keygen -t ed25519 -C "<email>"Linux & shellCreate an SSH keyWhat each part does
ssh-keygengenerate a key pair-t ed25519key type (ed25519 is the modern default)-C "<email>"comment stored in the key, to recognise it
Tip Creates ~/.ssh/id_ed25519 (private, keep secret) and id_ed25519.pub (public).
Linux & shell cheat sheet →ssh-copy-id <user>@<host>Linux & shellInstall your public key on a serverWhat each part does
ssh-copy-idappend your public key to ~/.ssh/authorized_keys on the server
wget <url>Linux & shellDownload a fileWhat each part does
wgetdownload to the current folder (curl -O <url> does the same)
nc -zv <host> <port>Linux & shellIs a TCP port open?What each part does
ncnetcat-zjust scan, send no data-vverbose: say "succeeded" or "refused"
traceroute <host>Linux & shellPath packets take to a hostWhat each part does
traceroutelist every hop (router) on the way; shows where it stops
ip aLinux & shellShow IP addressesWhat each part does
ip ashort for ip address: every interface with its IPs
ss -tulpnLinux & shellWhich process listens on which portWhat each part does
sssocket statistics (modern netstat)-tTCP sockets-uUDP sockets-llistening sockets only-pshow the owning process (needs sudo for other users’ processes)-nnumeric ports and addresses, no name lookups
sudo lsof -i :<port>Linux & shellWho is using a portWhat each part does
lsoflist open files (sockets are files too)-ionly network sockets:<port>filter to that port
ip -br addr; ip routeLinux & shellInterfaces and routesWhat each part does
ip -br addrevery interface with its addresses, one line each (-br = brief)ip routerouting table, including the default gateway
curl -sS -o /dev/null -w "%{http_code} %{time_total}s\n" <url>Linux & shellCheck an HTTP endpoint: status code and timeWhat each part does
-ssilent: no progress bar-Sbut still show errors-o /dev/nullthrow away the response body-w "…"print a custom line after the request: %{http_code} = status, %{time_total} = seconds
curl -fsSL <url> -o <file>Linux & shellDownload a file, following redirects, failing on HTTP errorsWhat each part does
-ffail (non-zero exit, no output) on HTTP 4xx/5xx-s -Squiet, but show errors-Lfollow redirects-o <file>write the body to <file>
sudo ufw status verboseLinux & shellFirewall status and rules (Ubuntu ufw)What each part does
ufw statusactive or not, and each allow/deny ruleverbosealso default policies and logging level
sudo ufw allow <port>/tcpLinux & shellAllow a port (ufw)CautionWhat each part does
ufw allowadd an allow rule (ufw allow from <ip> to any port <port> to restrict the source)<port>/tcpport and protocol
sudo firewall-cmd --list-allLinux & shellFirewall rules (RHEL firewalld)What each part does
firewall-cmd --list-allthe default zone's services, ports, rich rules and interfaces
sudo firewall-cmd --permanent --add-port=<port>/tcp && sudo firewall-cmd --reloadLinux & shellOpen a port permanently (firewalld)CautionWhat each part does
--permanentsave to config (without it the rule is lost on reload)--add-port=<port>/tcpopen the port in the default zone (or --add-service=https)--reloadapply the saved config
sudo iptables -L -n -v --line-numbersLinux & shellList iptables rules with countersWhat each part does
-Llist rules of the filter table-nnumeric, no DNS lookups-vpacket/byte counters and interfaces--line-numbersrule numbers, for deleting by number
sudo iptables -t nat -L -n -vLinux & shellList NAT rules (port forwards, Docker, Kubernetes)What each part does
-t natthe NAT table: DNAT port forwards and MASQUERADE rules
sudo nft list rulesetLinux & shellShow the full nftables rulesetWhat each part does
nft list rulesetevery table, chain and rule (newer distros use nftables under firewalld and iptables-nft)
openssl s_client -connect <host>:443 -servername <host> -showcerts </dev/nullLinux & shellShow a server's certificate and chainWhat each part does
s_client -connect <host>:443open a TLS connection-servername <host>send SNI, so you get the right certificate on shared IPs-showcertsprint every certificate the server sends</dev/nullclose the connection right after the handshake
openssl s_client -connect <host>:443 -servername <host> </dev/null 2>/dev/null | openssl x509 -noout -subject -issuer -datesLinux & shellWhen does a site's certificate expire?What each part does
openssl s_client ...fetch the certificate| openssl x509 -nooutparse it without printing the encoded certificate-subject -issuer -dateswho it is for, who signed it, notBefore and notAfter
openssl x509 -in <cert>.pem -noout -textLinux & shellRead a certificate fileWhat each part does
x509 -in <cert>.pema PEM certificate file-noout -textfull details: subject, SANs (DNS names), validity, key size
openssl x509 -noout -pubkey -in <cert>.pem | sha256sum; openssl pkey -pubout -in <key>.pem | sha256sumLinux & shellDoes this key belong to this certificate?What each part does
x509 -pubkeypublic key from the certificatepkey -puboutpublic key derived from the private keysha256sumthe two hashes must be identical
openssl req -new -newkey rsa:2048 -nodes -keyout <name>.key -out <name>.csr -subj "/CN=<domain>"Linux & shellCreate a private key and a CSRWhat each part does
req -newnew certificate signing request-newkey rsa:2048 -nodesgenerate a 2048-bit key, not encrypted with a passphrase-keyout / -outwhere to write the key and the CSR-subj "/CN=<domain>"subject; add -addext "subjectAltName=DNS:<domain>" for SANs
openssl req -x509 -newkey rsa:2048 -nodes -days 365 -keyout <name>.key -out <name>.crt -subj "/CN=<domain>"Linux & shellSelf-signed certificate for testingWhat each part does
req -x509output a self-signed certificate instead of a CSR-days 365valid for a year
openssl verify -CAfile <ca-bundle>.pem <cert>.pemLinux & shellCheck a certificate against a CA bundleWhat each part does
openssl verifyOK if the chain validates; otherwise the reason (expired, unable to get issuer)-CAfiletrusted CA and intermediates
openssl s_client -connect <host>:443 -tls1_2 </dev/null; openssl s_client -connect <host>:443 -tls1_3 </dev/nullLinux & shellWhich TLS versions does a server accept?What each part does
-tls1_2 / -tls1_3force one protocol version; a handshake failure means it's not supported
sudo tcpdump -i any -nn port <port>Linux & shellCapture traffic on a portWhat each part does
tcpdumppacket capture-i anyall interfaces-nndon't resolve names or portsport <port>filter: only traffic on that port (also host <ip>, tcp, udp)
sudo tcpdump -i <interface> -w <file>.pcap -c 10000 host <ip>Linux & shellSave a capture for WiresharkWhat each part does
-w <file>.pcapwrite raw packets to a file-c 10000stop after 10,000 packetshost <ip>only traffic to or from this IP
ip route get <ip>Linux & shellWhich route and source IP would be used?What each part does
ip route getthe exact route, gateway, interface and source address the kernel would use
mtr -rwc 50 <host>Linux & shellPath and packet loss to a hostWhat each part does
mtrtraceroute and ping combined, per hop-r -wreport mode with wide (untruncated) host names-c 5050 probes per hop
nmap -Pn -p 1-1024 <host>Linux & shellScan a host's open portsWhat each part does
nmapport scanner (only scan hosts you're allowed to)-Pnskip the ping check (many hosts block ping)-p 1-1024port range (or -p 22,80,443)
ss -sLinux & shellSocket summaryWhat each part does
ss -stotals of TCP states: established, time-wait, orphaned; spot connection leaks
ss -tn state established | awk 'NR>1 {split($4,a,":"); print a[1]}' | sort | uniq -c | sort -rn | headLinux & shellConnections per remote IPWhat each part does
ss -tn state establishedopen TCP connections, numericawk '...'take the peer address column and strip the portsort | uniq -c | sort -rn | headcount per IP, busiest first
ip neighLinux & shellARP / neighbour tableWhat each part does
ip neighIP to MAC mappings; FAILED or INCOMPLETE entries point to layer 2 problems
curl -sv --resolve <host>:443:<ip> https://<host>/Linux & shellTest a URL against a specific IP (skip DNS)What each part does
--resolve <host>:443:<ip>use this IP for that host and port, keeping the right SNI and Host header-svquiet progress, verbose headers and TLS
nc -l <port>Linux & shellListen on a port to test reachabilityWhat each part does
nc -l <port>listen; from another machine nc -zv <host> <port> or curl shows whether traffic gets through
Find & inspect66
docker ps -a | grep <container-id>DockerFind a container by ID or name in the full listWhat each part does
docker pslist containers (running only by default)-a--all: include stopped / exited containers too|pipe the table into grepgrep <container-id>keep only the row that contains that ID (a prefix like 3f2a is enough) or name
Tip Built-in alternative without grep: docker ps -a --filter id=<container-id> (or --filter name=<name>).
Docker cheat sheet →docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"DockerOnly running containers, compact tableWhat each part does
docker psrunning containers--format "table …"Go template output; "table" adds column headers{{.Names}} {{.Status}} {{.Ports}}fields to show; \t separates columns
docker ps -a --filter status=exited --filter name=<name>DockerFilter containers by state, name or imageWhat each part does
-aall containers--filter status=exitedonly exited ones (also: running, paused, restarting…)--filter name=<name>name contains <name>. Repeating --filter combines them
docker ps -qDockerJust the IDs (for scripting)docker inspect --format '{{.State.ExitCode}} OOMKilled={{.State.OOMKilled}}' <container>DockerWhy did it stop? Exit code and OOMWhat each part does
docker inspect <container>full JSON details of the container--format '…'Go template: print only the fields you ask for{{.State.ExitCode}}0 = clean exit, 137 = killed (often out of memory), 143 = SIGTERM{{.State.OOMKilled}}true if the kernel killed it for exceeding its memory limit
docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' <container>DockerContainer IP addressWhat each part does
range .NetworkSettings.Networksloop over every network the container is attached to{{.IPAddress}}print its IP on that network
docker stats --no-streamDockerLive CPU / memory per containerWhat each part does
docker statsresource usage of running containers--no-streamprint one snapshot and exit instead of refreshing
docker exec <container> envDockerPrint all environment variables of a running containerWhat each part does
docker exec <container>run a command inside the running containerenvprint every environment variable the container's processes see, KEY=value per line
Tip Needs a running container that has env (most images do; distroless ones don't). For a stopped container use the inspect version below.
Docker cheat sheet →docker exec <container> printenv <VAR>DockerPrint one environment variableWhat each part does
docker exec <container>run inside the containerprintenv <VAR>print only that variable's value; exit code 1 if it isn't set
docker inspect <container> --format '{{range .Config.Env}}{{println .}}{{end}}'DockerShow env vars from the container config (works when stopped)What each part does
docker inspect <container>read the container's stored configuration; no exec needed--format '...'Go template to pick fields{{range .Config.Env}}loop over the Env list (from the image ENV, -e and --env-file){{println .}}print each KEY=value on its own line
Tip Shows the configured env, not variables a process exported at runtime. Secrets passed with -e are visible here: anyone with docker access can read them.
Docker cheat sheet →docker image inspect <image>:<tag> --format '{{json .Config.Env}}'DockerShow env vars baked into an imageWhat each part does
docker image inspect <image>:<tag>metadata of a local image{{json .Config.Env}}the ENV values from the Dockerfile (PATH, versions...) as a JSON list
docker run --rm <image>:<tag> envDockerPrint the env a fresh container would getWhat each part does
docker run --rmstart a throwaway container, removed when it exits<image>:<tag>the image to testenvoverride the command: just print the environment
docker compose exec <service> envDockerPrint the env of a Compose serviceWhat each part does
docker compose exec <service>run inside the running service containerenvprint its environment, after .env and environment: substitution
Tip To check the values before starting anything, use docker compose config.
Docker cheat sheet →docker inspect <container> --format 'Entrypoint={{json .Config.Entrypoint}} Cmd={{json .Config.Cmd}}'DockerShow the entrypoint and command a container runsWhat each part does
docker inspect <container>container config{{json .Config.Entrypoint}}the ENTRYPOINT (the program that always runs){{json .Config.Cmd}}the CMD (default arguments, replaced by what you type after the image name)
docker inspect <container> --format '{{json .Mounts}}' | jqDockerShow mounts (volumes and bind mounts)What each part does
{{json .Mounts}}every mount: type, source on the host, destination in the container, read-only flag| jqpretty-print the JSON
docker inspect <container> --format '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}'DockerShow the container's IP address(es)What each part does
{{range .NetworkSettings.Networks}}loop over every network the container is attached to{{.IPAddress}}its IP on that network
docker inspect <container> --format 'restart={{.HostConfig.RestartPolicy.Name}} memory={{.HostConfig.Memory}} cpus={{.HostConfig.NanoCpus}}'DockerShow restart policy and resource limitsWhat each part does
{{.HostConfig.RestartPolicy.Name}}no, always, on-failure or unless-stopped{{.HostConfig.Memory}}memory limit in bytes (0 = unlimited){{.HostConfig.NanoCpus}}CPU limit in billionths of a CPU (1000000000 = 1 CPU, 0 = unlimited)
docker inspect <container> --format '{{json .State.Health}}' | jqDockerShow the health check status and last resultsWhat each part does
{{json .State.Health}}status (starting / healthy / unhealthy), failing streak, and the output of the last checks| jqpretty-print
docker inspect <container> --format '{{json .Config.Labels}}' | jqDockerShow labels (Compose project, versions, maintainers)What each part does
{{json .Config.Labels}}all labels as JSON, e.g. com.docker.compose.service and org.opencontainers.image.version| jqpretty-print
docker exec <container> cat /etc/os-releaseDockerWhich OS and version is the container based on?What each part does
docker exec <container>run inside the containercat /etc/os-releasedistro name and version, e.g. Debian 12, Alpine 3.20, UBI 9
docker exec <container> sh -c 'dpkg -l 2>/dev/null || rpm -qa 2>/dev/null || apk info -v'DockerList installed OS packages with versions (any distro)What each part does
sh -c '...'run a small shell script inside the containerdpkg -lDebian / Ubuntu packages and versions2>/dev/null ||hide the error and try the next tool if this one doesn't existrpm -qaRHEL / UBI / Amazon Linux packagesapk info -vAlpine packages with versions
docker exec <container> sh -c 'dpkg-query -W <package> 2>/dev/null || rpm -q <package> 2>/dev/null || apk info -v <package>'DockerVersion of one package in a containerWhat each part does
dpkg-query -W <package>Debian / Ubuntu: name and installed versionrpm -q <package>RHEL family: name-version-releaseapk info -v <package>Alpine: name-version
docker run --rm <image>:<tag> <program> --versionDockerVersion of the app runtime in an imageWhat each part does
docker run --rm <image>:<tag>throwaway container from the image<program> --versione.g. node --version, python3 --version, java -version, nginx -v
docker image inspect <image>:<tag> --format '{{index .Config.Labels "org.opencontainers.image.version"}}'DockerImage version labels (OCI annotations)What each part does
docker image inspect <image>:<tag>image metadata{{index .Config.Labels "..."}}read one label; the OCI version label is set by many official images and good pipelines
docker image inspect <image>:<tag> --format '{{.Id}} {{index .RepoDigests 0}} {{.Created}} {{.Os}}/{{.Architecture}}'DockerImage ID, digest, created date and architectureWhat each part does
{{.Id}}local image ID{{index .RepoDigests 0}}registry digest (repo@sha256:...) to pin exactly this image{{.Created}}build date{{.Os}}/{{.Architecture}}platform, e.g. linux/amd64 or linux/arm64
docker inspect <container> --format '{{.Config.Image}} {{.Image}}'DockerWhich image (and digest) is a container running?What each part does
{{.Config.Image}}the name:tag it was started from{{.Image}}the exact image ID, so you can tell if :latest has moved since
docker manifest inspect <image>:<tag> | jq '.manifests[].platform'DockerCheck which platforms an image supports, without pullingWhat each part does
docker manifest inspectread the image manifest from the registry| jq '.manifests[].platform'list os/architecture of every variant (multi-arch images)
docker scout quickview <image>:<tag>DockerQuick vulnerability overview of an imageWhat each part does
docker scout quickviewsummary of known CVEs by severity and base image update advice (Docker Scout plugin)<image>:<tag>local or registry image
Tip docker scout cves <image> lists every CVE. Trivy does the same without Docker's plugin.
Docker cheat sheet →kubectl get po -n <namespace>KubernetesList podsWhat each part does
kubectl getlist resourcesposhort name for pods: NAME, READY, STATUS, RESTARTS, AGE-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get po -o wide -n <namespace>KubernetesList pods with node and IPWhat each part does
popods-o wideadd the pod IP, the node it runs on and nominated node-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get svc -n <namespace>KubernetesList servicesWhat each part does
svcshort name for services: TYPE, CLUSTER-IP, EXTERNAL-IP, PORT(S)-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get svc -o wide -n <namespace>KubernetesList services with their selectorsWhat each part does
svc -o wideadd the SELECTOR column: which pod labels the service sends traffic to-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get endpointslices -l kubernetes.io/service-name=<service> -n <namespace>KubernetesWhich pods is a service sending traffic to?What each part does
endpointslicesthe actual pod IPs:ports behind services (kubectl get ep <service> on older clusters)-l kubernetes.io/service-name=<service>only the slices of this service-n <namespace>in this namespace (default: the context's namespace; -A for all)
Tip Empty ENDPOINTS means the selector matches no ready pods: compare kubectl get svc -o wide with kubectl get po --show-labels.
Kubernetes cheat sheet →kubectl get deploy -n <namespace>KubernetesList deploymentsWhat each part does
deploydeployments: READY (ready/desired), UP-TO-DATE, AVAILABLE-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get rs -n <namespace>KubernetesList ReplicaSetsWhat each part does
rsReplicaSets; old ones with 0 replicas are kept for rollbacks-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get sts,ds -n <namespace>KubernetesList StatefulSets and DaemonSetsWhat each part does
stsStatefulSetsdsDaemonSets: desired / current / ready per node-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get ing -AKubernetesList ingressesWhat each part does
ingingresses: class, hosts, address, ports-Aall namespaces
kubectl get cm,secret -n <namespace>KubernetesList ConfigMaps and SecretsWhat each part does
cmConfigMapssecretSecrets (values are not shown)-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get pv,pvc -AKubernetesList volumes and claimsWhat each part does
pvPersistentVolumes (cluster-wide): capacity, status, claimpvcPersistentVolumeClaims: Bound / Pending-Aall namespaces for the claims
kubectl get scKubernetesList storage classesWhat each part does
scStorageClasses; (default) marks the one used when a PVC names none
kubectl get jobs,cj -n <namespace>KubernetesList jobs and cronjobsWhat each part does
jobsJobs: completions, durationcjCronJobs: schedule, last schedule, active-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get hpa -n <namespace>KubernetesList autoscalersWhat each part does
hpaHorizontalPodAutoscalers: target metric vs current, min/max/current replicas-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get sa -n <namespace>KubernetesList service accountsWhat each part does
saServiceAccounts-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get netpol -n <namespace>KubernetesList network policiesWhat each part does
netpolNetworkPolicies and the pods they select-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get crdKubernetesList custom resource typesWhat each part does
crdCustomResourceDefinitions installed by operators and add-ons
kubectl api-resources --sort-by=name -o wideKubernetesEvery short name and resource typeWhat each part does
api-resourcesevery resource type: SHORTNAMES (po, svc, deploy...), API group, namespaced, verbs--sort-by=namealphabetical-o wideinclude supported verbs
kubectl get po -l 'env in (prod,staging),tier!=frontend'KubernetesPods by set-based label selectorWhat each part does
-l '...'label selectorenv in (prod,staging)label env is one of thesetier!=frontendand tier is not frontend
kubectl get po -A -o wide --field-selector spec.nodeName=<node>KubernetesPods on a specific nodeWhat each part does
-A -o wideall namespaces, with node column--field-selector spec.nodeName=<node>only pods scheduled on that node
kubectl get po -o name -n <namespace>KubernetesJust the names (for scripts)What each part does
-o nameprint type/name per line, e.g. pod/api-7d9f, ready for xargs-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get po -A -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.image}{"\n"}{end}{end}' | sort | uniq -cKubernetesEvery image running in the clusterWhat each part does
-o jsonpath='...'loop over pods and their containers, print each image| sort | uniq -ccount pods per image
kubectl get po -w -n <namespace>KubernetesWatch resources changeWhat each part does
-wkeep printing changes (status, restarts) until Ctrl+C-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl get pods -A -o wideKubernetesPods in every namespace, with node and IPWhat each part does
kubectl get podslist pods-A--all-namespaces-o wideextra columns: node, pod IP, nominated node
kubectl get pods -A | grep <name>KubernetesFind a pod by name fragmentWhat each part does
kubectl get pods -Aall pods in all namespaces (columns: NAMESPACE NAME READY STATUS…)|pipe the table into grepgrep <name>keep rows containing <name> (pod name, namespace or status like CrashLoopBackOff)
kubectl get pods -A --field-selector=status.phase!=RunningKubernetesPods that are not RunningWhat each part does
--field-selectorfilter on object fields server-sidestatus.phase!=Runningphase is anything except Running (Pending, Failed, Succeeded, Unknown)
kubectl get pods -l app=<app> --show-labelsKubernetesPods with a labelWhat each part does
-l app=<app>--selector: label must match (use "!key" to exclude, key in (a,b) for sets)--show-labelsadd a LABELS column
kubectl get pods -n <namespace> --sort-by=.status.containerStatuses[0].restartCountKubernetesRecently restarted pods, sortedWhat each part does
--sort-by=<jsonpath>sort rows by a field of the object.status.containerStatuses[0].restartCountrestart count of the first container: crash-looping pods end up last
kubectl get pods -o jsonpath='{.items[*].metadata.name}'KubernetesJust the pod namesWhat each part does
-o jsonpath=…print fields using a JSONPath template{.items[*].metadata.name}the name of every item in the list
kubectl get pods -o custom-columns='NAME:.metadata.name,IMAGE:.spec.containers[*].image'KubernetesCustom table: pod and imageWhat each part does
-o custom-columns=…build your own tableNAME:.metadata.namecolumn header : JSONPath of the valueIMAGE:.spec.containers[*].imageimages of all containers
kubectl api-resourcesKubernetesWhat resource types exist (and their short names)What each part does
api-resourcesevery resource type with short name (po, svc, deploy…), API group and whether it is namespaced
kubectl explain deployment.spec.strategyKubernetesDocs for a fieldWhat each part does
explainbuilt-in documentation for resource fieldsdeployment.spec.strategypath to the field you want to understand
kubectl describe svc <service> -n <namespace>KubernetesDescribe a serviceWhat each part does
describe svctype, selector, ports, target ports, endpoints and events-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl run dnstest --rm -it --restart=Never --image=busybox:1.36 -- nslookup <service>.<namespace>.svc.cluster.localKubernetesTest DNS from inside the clusterWhat each part does
kubectl run dnstest --rm -it --restart=Neverthrowaway pod, removed when done--image=busybox:1.36small image with nslookup<service>.<namespace>.svc.cluster.locala service's full DNS name
kubectl run curltest --rm -it --restart=Never --image=curlimages/curl -- curl -sv http://<service>.<namespace>:<port>/KubernetesCall a service from inside the clusterWhat each part does
--image=curlimages/curlimage with curlhttp://<service>.<namespace>:<port>/service DNS name and port: tests the path pods use
kubectl port-forward deploy/<deployment> <local-port>:<container-port> -n <namespace>KubernetesPort-forward to a deployment or podWhat each part does
deploy/<deployment>picks one pod of the deployment (also pod/<pod>, svc/<service>)<local-port>:<container-port>localhost port : port in the pod-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl proxy --port=8001KubernetesOpen a local proxy to the API serverWhat each part does
kubectl proxyauthenticated proxy: http://localhost:8001/api/... reaches the API, and services via /api/v1/namespaces/<ns>/services/<svc>/proxy/--port=8001local port
kubectl get --raw='/readyz?verbose'KubernetesCheck the API server healthWhat each part does
get --rawcall an API path directly/readyz?verboseeach readiness check with ok/failed (also /livez)
Logs & monitoring19
systemctl status <unit> --no-pager -lLinux & shellStatus and recent logs of a serviceWhat each part does
systemctl status <unit>state, PID, last exit code and the last log lines--no-pagerprint directly instead of opening less-ldon't truncate long lines
sudo systemctl enable --now <unit>Linux & shellStart at boot and start nowWhat each part does
enablecreate the links so the unit starts at boot--nowalso start it right away
sudo systemctl daemon-reload && sudo systemctl restart <unit>Linux & shellReload unit files after editing themWhat each part does
daemon-reloadre-read unit files (does not restart services)&&only if that worked…restart <unit>stop then start the service
journalctl -u <unit> -f -n 100Linux & shellFollow a service logWhat each part does
-u <unit>only messages from that unit-ffollow new entries-n 100start with the last 100 lines
journalctl -p err -b --no-pagerLinux & shellErrors since bootWhat each part does
-p errpriority "err" and more severe (crit, alert, emerg)-bcurrent boot only (-b -1 = previous boot)--no-pagerplain output
journalctl -u <unit> --since "1 hour ago" --until nowLinux & shellLogs in a time windowWhat each part does
--sincestart time: absolute ("2026-11-20 10:00") or relative ("1 hour ago", "yesterday")--untilend time
docker logs -f --tail 200 -t <container>DockerFollow the last 200 log lines with timestampsWhat each part does
docker logs <container>the container's stdout/stderr-f--follow: keep streaming new lines--tail 200start from the last 200 lines (alias -n)-t--timestamps: prefix each line with its time
docker logs --since 15m <container> 2>&1 | grep -i errorDockerLogs from the last 15 minutes, errors onlyWhat each part does
--since 15monly lines from the last 15 minutes (also 1h30m or an RFC3339 time)2>&1merge stderr into stdout, so grep also sees error output| grep -i errorkeep lines containing "error", any case
docker exec -it <container> shDockerOpen a shell inside a running containerWhat each part does
docker exec <container>run a command in a running container-i--interactive: keep stdin open-t--tty: allocate a terminalshthe command to run (use bash if the image has it)
docker exec -e <KEY>=<value> -w <dir> <container> <cmd>DockerRun a one-off command with env and workdirWhat each part does
-e <KEY>=<value>set an environment variable for this command only-w <dir>working directory inside the container<cmd>command to run; wrap chains as sh -c "a && b"
docker cp <container>:<path> ./ ; docker cp ./<file> <container>:<path>DockerCopy a file out of / into a containerWhat each part does
docker cp <container>:<path> ./container → current host directory;thendocker cp ./<file> <container>:<path>host → container
kubectl describe pod <pod> -n <namespace>KubernetesWhy is a pod not starting?What each part does
describe pod <pod>status, conditions, container states (Last State / Exit Code) and events at the bottom-n <namespace>namespace of the pod
Tip Look for ImagePullBackOff, FailedScheduling, OOMKilled, probe failures in Events.
Kubernetes cheat sheet →kubectl get events -n <namespace> --sort-by=.metadata.creationTimestampKubernetesRecent events, newest lastWhat each part does
get eventscluster events (scheduling, pulls, kills, probe failures)--sort-by=.metadata.creationTimestampoldest → newest
kubectl events -n <namespace> --types=WarningKubernetesOnly warning eventsWhat each part does
kubectl eventsnewer events subcommand--types=Warningonly Warning-type events
kubectl logs -f <pod> -n <namespace> --tail=200KubernetesFollow logs of a podWhat each part does
logs <pod>container's stdout/stderr-fstream new lines--tail=200start from the last 200 lines
kubectl logs <pod> -c <container> --previousKubernetesLogs of the crashed (previous) containerWhat each part does
-c <container>pick a container in a multi-container pod--previouslogs of the previous instance, i.e. the one that crashed
kubectl logs -l app=<app> --all-containers --prefix -fKubernetesLogs from all pods with a labelWhat each part does
-l app=<app>every pod matching the label--all-containersall containers in each pod--prefixprefix lines with pod/container name-ffollow
kubectl logs deploy/<deployment> --since=1h | grep -i errorKubernetesGrep logs for errorsWhat each part does
deploy/<deployment>logs from one pod of the deployment--since=1honly the last hour| grep -i errorkeep lines with "error", any case
kubectl top pod -n <namespace> --sort-by=memory --containersKubernetesCPU / memory usageWhat each part does
top podlive usage (needs metrics-server)--sort-by=memoryhighest memory first (or cpu)--containersper container instead of per pod
Shell in, port-forward & copy4
kubectl exec -it <pod> -n <namespace> -- shKubernetesShell into a podWhat each part does
exec <pod>run a command in a container of the pod-itinteractive stdin + terminal--everything after this is the command, not kubectl flagsshthe shell (bash if available)
kubectl port-forward svc/<service> <local-port>:<service-port> -n <namespace>KubernetesReach a service from your laptopWhat each part does
port-forwardtunnel a local port into the clustersvc/<service>target a service (or pod/<pod>, deploy/<name>)<local-port>:<service-port>listen on localhost:<local-port>, forward to <service-port>
kubectl cp <namespace>/<pod>:<path> ./<file>KubernetesCopy files out of / into a podWhat each part does
cpcopy files (needs tar inside the container)<namespace>/<pod>:<path>source in the pod; swap the arguments to copy into the pod
kubectl debug <pod> -it --image=busybox:1.36 --target=<container>KubernetesAttach a debug container to a podWhat each part does
debug <pod>add an ephemeral debug container-itinteractive terminal--image=busybox:1.36image with the tools you need--target=<container>share that container's process namespace
Build, run, deploy & roll back128
docker run -d --name <name> -p <host-port>:<container-port> <image>:<tag>DockerRun a service in the background with a port and a nameWhat each part does
docker runcreate and start a container-d--detach: run in the background and print the ID--name <name>give it a fixed name instead of a random one-p <host-port>:<container-port>publish a container port on the host (binds all interfaces; use 127.0.0.1:<host-port>:… for local only)<image>:<tag>image to run (pin a tag, avoid latest)
docker run -it --rm <image> shDockerThrow-away interactive containerWhat each part does
-itinteractive + terminal--rmdelete the container (and anonymous volumes) when it exitsshcommand to run instead of the image default
docker run -d -e <KEY>=<value> --env-file .env -v <host-path>:<container-path>:ro -m 512m --cpus 1 --restart unless-stopped <image>DockerEnv vars, volume and limitsWhat each part does
-e <KEY>=<value>set one environment variable--env-file .envload KEY=value lines from a file-v <host-path>:<container-path>:robind-mount a host folder, read-only-m 512mmemory limit (exceeding it → OOM kill, exit 137)--cpus 1at most one CPU worth of time--restart unless-stoppedrestart automatically unless you stopped it yourself
docker build -t <registry>/<image>:<tag> -f <Dockerfile> .DockerBuild and tag an imageWhat each part does
docker buildbuild an image (BuildKit)-t <registry>/<image>:<tag>name and tag for the result-f <Dockerfile>which Dockerfile (default ./Dockerfile).build context: the folder sent to the builder (.dockerignore trims it)
docker build --no-cache --pull --target <stage> --build-arg <KEY>=<value> -t <image>:<tag> .DockerClean rebuild of one stage with a build argWhat each part does
--no-cacheignore cached layers--pullalways check for a newer base image--target <stage>stop at a named stage of a multi-stage Dockerfile--build-arg <KEY>=<value>value for an ARG in the Dockerfile
docker tag <image>:<tag> <registry>/<image>:<tag> && docker push <registry>/<image>:<tag>DockerTag and push to a registryWhat each part does
docker tag <src> <target>add another name to an existing image&&only if tagging workeddocker push <target>upload it (run docker login <registry> first)
docker history --no-trunc <image>DockerImage layers and what created themWhat each part does
docker historyone row per layer with its size--no-truncshow the full command that created each layer
docker compose up -d --buildDockerBuild and start everything in the backgroundWhat each part does
docker composeCompose v2 (plugin; not the old docker-compose binary)upcreate and start the services-ddetached--buildbuild images before starting
docker compose up -d --force-recreate --remove-orphans --waitDockerRecreate cleanly and wait until healthyWhat each part does
--force-recreaterecreate containers even if nothing changed--remove-orphansremove containers for services no longer in the file--waitwait until services are running/healthy (implies -d)
docker compose logs -f --tail 100 <service>DockerFollow logs of one serviceWhat each part does
logs <service>logs of that service (omit for all)-ffollow--tail 100start from the last 100 lines
docker compose exec <service> sh; docker compose run --rm <service> <cmd>DockerShell into a service / run a one-off taskWhat each part does
exec <service> shshell in the already-running service containerrun --rm <service> <cmd>start a new temporary container for a one-off command, removed afterwards
docker compose -f compose.yaml -f compose.prod.yaml -p <project> up -dDockerUse several compose files and a project nameWhat each part does
-f compose.yaml -f compose.prod.yamlmerge files in order; later files override earlier ones-p <project>project name (prefix for container/network names)
docker compose configDockerSee the final merged configWhat each part does
configparse, merge and print the effective compose file (great for checking env substitution)
docker compose down -vDockerStop and remove the stack (and its volumes)DestructiveWhat each part does
downstop and remove containers and networks-valso remove named volumes declared in the file: deletes data
docker top <container>DockerProcesses running inside a containerWhat each part does
docker topps output for the container's processes, as seen from the host (PIDs are host PIDs)<container>name or ID
docker diff <container>DockerFiles changed inside a container since it startedWhat each part does
docker difflist files added (A), changed (C) or deleted (D) in the container's writable layer
Tip Handy to find where an app writes data that should be in a volume.
Docker cheat sheet →docker kill -s <signal> <container>DockerSend a signal to a containerCautionWhat each part does
docker killsend a signal to the main process (default SIGKILL)-s <signal>e.g. HUP to reload nginx config, TERM for a graceful stop
docker pause <container>; docker unpause <container>DockerPause and resume a containerWhat each part does
docker pausefreeze all processes (cgroup freezer); memory stays, no CPU useddocker unpauselet them run again
docker wait <container>DockerWait for a container to exit and get its exit codeWhat each part does
docker waitblock until the container stops, then print its exit code (useful in scripts)
docker update --memory 1g --memory-swap 1g --cpus 1.5 --restart unless-stopped <container>DockerChange memory, CPU or restart policy of a running containerWhat each part does
docker updatechange settings live, no restart--memory 1g --memory-swap 1ghard memory limit; equal swap value means no extra swap--cpus 1.5at most 1.5 CPUs--restart unless-stoppednew restart policy
docker attach --sig-proxy=false <container>DockerAttach to a container's main processWhat each part does
docker attachconnect your terminal to the main process's stdin/stdout--sig-proxy=falseso Ctrl+C doesn't kill the container; detach with Ctrl+P Ctrl+Q
Tip Usually you want docker logs -f or docker exec instead.
Docker cheat sheet →docker events --filter container=<container> --since 30mDockerWatch Docker events liveWhat each part does
docker eventsstream of daemon events: create, start, die, oom, health_status, kill...--filter container=<container>only this container (also type=, event=, image=)--since 30minclude events from the last 30 minutes
docker commit -m "<message>" <container> <image>:<tag>DockerSave a container's current state as an imageWhat each part does
docker commitsnapshot the container's filesystem into a new image-m "<message>"commit message<image>:<tag>name for the new image
Tip Good for debugging or forensics; for real images use a Dockerfile.
Docker cheat sheet →docker create --name <name> <image>:<tag>DockerCreate a container without starting itWhat each part does
docker createcreate the container (pull if needed) but don't run it--name <name>its name; start later with docker start
docker build --build-arg <ARG>=<value> --target <stage> --no-cache -t <image>:<tag> .DockerBuild with build args, a target stage and no cacheWhat each part does
--build-arg <ARG>=<value>set an ARG declared in the Dockerfile (not for secrets: they stay in history)--target <stage>stop at this stage of a multi-stage build--no-cacherebuild every layer-t <image>:<tag>name the result.build context
docker build -f <path>/Dockerfile.prod -t <image>:<tag> .DockerUse a different DockerfileWhat each part does
-f <path>/Dockerfile.prodDockerfile to use.build context (can differ from the Dockerfile's folder)
docker build --secret id=npmrc,src=$HOME/.npmrc -t <image>:<tag> .DockerPass a secret to a build without leaving it in the imageWhat each part does
--secret id=npmrc,src=...mount a file only during the RUN step that asks for itDockerfile sideRUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
docker buildx build --platform linux/amd64,linux/arm64 -t <registry>/<image>:<tag> --push .DockerBuild for several CPU architectures and pushWhat each part does
docker buildx buildBuildKit builder with multi-platform support--platform linux/amd64,linux/arm64build both (Intel/AMD servers and ARM like Graviton or Apple Silicon)--pushpush the multi-arch image straight to the registry
docker buildx ls; docker buildx create --name <builder> --useDockerList and create buildx buildersWhat each part does
docker buildx lsbuilders and the platforms they supportdocker buildx create --usenew builder (docker-container driver) and make it the default
docker build --progress=plain -t <image>:<tag> .DockerBuild with plain progress output (CI logs)What each part does
--progress=plainfull, line-by-line output of every step instead of the collapsing TTY view
docker save -o <file>.tar <image>:<tag>DockerSave an image to a file (no registry)What each part does
docker saveexport one or more images with all layers and tags-o <file>.tarwrite to a tar file
docker load -i <file>.tarDockerLoad an image from a fileWhat each part does
docker loadimport images saved with docker save-i <file>.tarinput file (also reads .tar.gz)
docker save <image>:<tag> | gzip | ssh <user>@<host> 'gunzip | docker load'DockerCopy an image to another host over SSHWhat each part does
docker save <image>:<tag>stream the image as tar| gzipcompress it| ssh <user>@<host> '...'send it to the other machinegunzip | docker loadunpack and load it there
docker export <container> -o <file>.tarDockerExport a container's filesystemWhat each part does
docker exportflatten the container's filesystem into a tar (no layers, history or metadata)-o <file>.taroutput file
docker initDockerGenerate a Dockerfile, compose file and .dockerignoreWhat each part does
docker initasks about your project (Node, Python, Go...) and writes starter Docker files
docker compose ps -aDockerStatus of the stack's containersWhat each part does
docker compose pscontainers of this project: service, state, health, ports-ainclude stopped ones
docker compose restart <service>; docker compose stop <service>DockerRestart / stop one serviceWhat each part does
restart <service>restart the container (config changes need up -d instead)stop <service>stop without removing
docker compose build --pull <service> && docker compose up -d <service>DockerRebuild images and recreateWhat each part does
build --pullrebuild, pulling newer base imagesup -d <service>recreate the container with the new image
docker compose pullDockerPull newer images for all servicesWhat each part does
docker compose pulldownload the image of every service; follow with up -d to use them
docker compose up -d --scale <service>=3DockerRun several replicas of a serviceWhat each part does
--scale <service>=3run 3 containers of the service (don't fix a host port or container_name)
docker compose --profile <profile> up -dDockerStart optional services with a profileWhat each part does
--profile <profile>also start services marked profiles: [<profile>], e.g. debug or tools
docker compose watchDockerRebuild automatically when files changeWhat each part does
docker compose watchsync or rebuild services on file changes, per the develop.watch section
docker compose top; docker compose imagesDockerProcesses and images of the stackWhat each part does
docker compose topprocesses in each service containerdocker compose imagesimage and tag each container uses
docker compose cp <service>:<path> ./DockerCopy a file out of a servicedocker swarm init --advertise-addr <ip>DockerTurn this host into a swarm managerWhat each part does
docker swarm initcreate a single-node swarm with this host as manager--advertise-addr <ip>the address other nodes use to reach it
docker swarm join-token workerDockerGet the join command for workersWhat each part does
join-token workerprint the docker swarm join command (use manager for extra managers)
docker node lsDockerList nodesdocker service create --name <service> --replicas 3 -p 80:80 <image>:<tag>DockerCreate a replicated serviceWhat each part does
docker service createa long-running service the swarm keeps alive--replicas 33 tasks spread over the nodes-p 80:80publish through the routing mesh on every node
docker service ls; docker service ps <service>DockerList services and where their tasks runWhat each part does
docker service lsservices with replicas running/desireddocker service ps <service>each task, its node, state and errors
docker service scale <service>=5DockerScale a servicedocker service update --image <image>:<new-tag> <service>; docker service rollback <service>DockerRolling update to a new image, and roll backWhat each part does
service update --imagerolling replace of tasks with the new imageservice rollbackgo back to the previous spec
docker service logs -f <service>DockerLogs of all tasks of a servicedocker stack deploy -c compose.yaml <stack>; docker stack rm <stack>DockerDeploy and remove a stack from a compose fileCautionWhat each part does
stack deploy -c compose.yaml <stack>create or update all services in the filestack rm <stack>remove the stack's services and networks
printf '%s' "$VALUE" | docker secret create <name> -DockerStore a secret for servicesWhat each part does
printf '%s' "$VALUE"the secret value without a trailing newlinedocker secret create <name> -store it encrypted in the swarm; services mount it at /run/secrets/<name>
kubectl diff -f <dir> && kubectl apply -f <dir>KubernetesPreview then apply manifestsWhat each part does
diff -f <dir>show what would change on the server&&continue only if diff ran without error (diff exits 1 when there are changes; use ; instead if you want to apply anyway)apply -f <dir>create or update every manifest in the folder
kubectl set image deployment/<deployment> <container>=<image>:<tag> -n <namespace>KubernetesChange the image of a deploymentCautionWhat each part does
set imageupdate container images → triggers a rolling updatedeployment/<deployment>which deployment<container>=<image>:<tag>container name in the pod spec = new image
kubectl rollout status deployment/<deployment> --timeout=5mKubernetesWait for the rollout to finishWhat each part does
rollout statuswatch progress until done or failed--timeout=5mgive up (non-zero exit) after 5 minutes: good for CI
kubectl rollout history deployment/<deployment>; kubectl rollout undo deployment/<deployment> --to-revision=<n>KubernetesHistory and rollbackCautionWhat each part does
rollout historylist revisionsrollout undogo back to the previous revision--to-revision=<n>or to a specific revision from the history
kubectl rollout restart deployment/<deployment> -n <namespace>KubernetesRestart all pods of a deploymentCautionWhat each part does
rollout restartrolling restart without changing the spec (picks up new ConfigMap/Secret values)
kubectl scale deployment/<deployment> --replicas=<n>KubernetesScale replicasCautionWhat each part does
scaleset the desired replica count--replicas=<n>new count (0 stops the app)
kubectl create deployment <name> --image=<image> --dry-run=client -o yaml > deploy.yamlKubernetesGenerate a manifest without creating anythingWhat each part does
create deploymentbuild a Deployment object--dry-run=clientdon't send it to the cluster-o yamlprint it as YAML> deploy.yamlsave to a file to edit and commit
kubectl run <name> --image=<image> --port=<port> --dry-run=client -o yaml > pod.yamlKubernetesGenerate a pod manifestWhat each part does
kubectl run <name> --image=<image>a single pod (the old --generator flag is gone)--dry-run=client -o yamlprint YAML instead of creating> pod.yamlsave to edit
kubectl expose deploy <deployment> --port=<port> --target-port=<container-port> --dry-run=client -o yaml > svc.yamlKubernetesGenerate a service manifestWhat each part does
expose deploy <deployment>service selecting the deployment's pods--port / --target-portservice port / container port--dry-run=client -o yamlYAML only
kubectl create job <job-name> --from=cronjob/<cronjob> -n <namespace>KubernetesCreate a job from a cronjob (run it now)What each part does
create job --from=cronjob/<cronjob>one-off Job using the CronJob's template-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl create cronjob <name> --image=<image> --schedule='*/5 * * * *' -- <command>KubernetesCreate a cronjobWhat each part does
--schedule='...'cron schedule-- <command>what the container runs
kubectl get deploy <deployment> -n <namespace> -o yaml > deploy.yamlKubernetesExport an existing object as clean YAMLWhat each part does
-o yamlthe full object; remove status, metadata.uid, resourceVersion, managedFields before re-applying (--export no longer exists; the kubectl-neat plugin strips them)
kubectl apply -R -f <dir>KubernetesApply a directory recursivelyWhat each part does
-Rrecurse into subdirectories-f <dir>every manifest in it
kubectl apply -k <overlay-dir>KubernetesApply a Kustomize overlayWhat each part does
-k <dir>render kustomization.yaml and apply; kubectl kustomize <dir> just prints it
kubectl apply --server-side -f <file>KubernetesServer-side applyWhat each part does
--server-sidethe API server merges and tracks field ownership; needed for large CRDs
kubectl replace --force -f <file>KubernetesReplace an object (delete + recreate)CautionWhat each part does
replace --forcedelete and recreate: for fields that can't be changed in place
kubectl wait --for=condition=Ready pod -l app=<app> --timeout=120s -n <namespace>KubernetesWait until pods are readyWhat each part does
kubectl wait --for=condition=Readyblock until the condition is true (also --for=delete, --for=jsonpath=...)pod -l app=<app>which objects--timeout=120sfail after 2 minutes
kubectl patch deploy <deployment> -n <namespace> -p '{"spec":{"replicas":3}}'KubernetesPatch a field (strategic merge)CautionWhat each part does
patchchange part of a live object without a full manifest-p '{...}'JSON or YAML snippet merged into the object
kubectl patch svc <service> --type=json -p '[{"op":"replace","path":"/spec/type","value":"NodePort"}]'KubernetesPatch with a JSON patchCautionWhat each part does
--type=jsonRFC 6902 operations: add, remove, replace at a path-p '[...]'the operations
kubectl label po <pod> <key>=<value>; kubectl label po <pod> <key>-KubernetesAdd / remove a labelWhat each part does
<key>=<value>add (add --overwrite to change)<key>-remove the label; also a way to take a pod out of a service for debugging
kubectl annotate deploy <deployment> <key>='<value>' --overwriteKubernetesAdd an annotationWhat each part does
annotatenon-identifying metadata read by tools--overwritereplace an existing value
kubectl autoscale deploy <deployment> --min=2 --max=10 --cpu-percent=80KubernetesAutoscale a deploymentWhat each part does
autoscalecreate an HPA--min / --maxreplica bounds--cpu-percent=80target average CPU vs requests (pods need CPU requests)
kubectl set resources deploy <deployment> -c <container> --requests=cpu=100m,memory=128Mi --limits=memory=256MiKubernetesSet CPU / memory requests and limitsCautionWhat each part does
set resourceschange resources in the pod template (rollout follows)--requests / --limitsvalues per container
kubectl rollout pause deploy/<deployment>; kubectl rollout resume deploy/<deployment>KubernetesPause and resume a rolloutWhat each part does
rollout pausestop rolling out; batch several changesrollout resumeroll them out together
kubectl rollout history deploy/<deployment> --revision=<n>KubernetesDetails of one rollout revisionWhat each part does
--revision=<n>show the pod template (images, env) of that revision before undoing to it
kubectl scale sts <statefulset> --replicas=<n> -n <namespace>KubernetesScale a StatefulSetWhat each part does
scale stspods are added/removed in order (highest ordinal first on scale-down)
terraform init -upgradeTerraform & HelmInitialise and upgrade providersWhat each part does
initdownload providers/modules and configure the backend-upgradepick the newest versions allowed by the constraints
terraform fmt -recursive -check && terraform validateTerraform & HelmFormat and validateWhat each part does
fmt -recursiveformat .tf files in sub-folders too-checkdon't change files; exit non-zero if formatting is needed (CI)validatecheck syntax and internal consistency (no API calls)
terraform plan -var-file=<env>.tfvars -out=tfplanTerraform & HelmPlan with a var file and save the planWhat each part does
plancompute what would change-var-file=<env>.tfvarsload variable values from a file (repeatable)-out=tfplansave this exact plan to apply later (contains values in clear text: keep it private)
terraform apply tfplanTerraform & HelmApply exactly the reviewed planCautionWhat each part does
apply tfplanapply the saved plan with no re-planning and no prompt
terraform plan -input=false -no-color -detailed-exitcode -out=tfplanTerraform & HelmCI-friendly plan: did anything change?What each part does
-input=falsenever prompt for variables-no-colorplain output for logs-detailed-exitcodeexit 0 = no changes, 1 = error, 2 = changes present
terraform plan -target=<address> -out=tfplanTerraform & HelmPlan only one resource (exceptional cases)What each part does
-target=<address>limit to that resource and its dependencies (use sparingly)
terraform plan -replace=<address> -out=tfplanTerraform & HelmForce replacement of one resourceCautionWhat each part does
-replace=<address>plan to destroy and recreate it (successor of taint)
terraform -chdir=<dir> planTerraform & HelmRun in another folder without cdWhat each part does
-chdir=<dir>global option, goes before the subcommand
terraform workspace list; terraform workspace new <name>; terraform workspace select <name>Terraform & HelmList, create and switch workspacesWhat each part does
workspace listworkspaces; * marks the current oneworkspace newnew empty state for the same codeworkspace selectswitch
terraform plan -generate-config-out=generated.tfTerraform & HelmImport an existing resource (block, Terraform 1.5+)What each part does
import block in codeimport { to = aws_s3_bucket.logs id = "my-logs" }-generate-config-outwrite matching resource code for you to review
terraform import <address> <id>Terraform & HelmImport an existing resource (CLI)What each part does
importrecord a real resource in state<address>resource in your code, e.g. aws_s3_bucket.logs<id>the provider's ID for it
terraform plan -destroy -out=destroy.tfplanTerraform & HelmPlan destroying everythingDestructiveWhat each part does
-destroyplan to delete every managed resource-outsave it; apply with terraform apply destroy.tfplan
terraform destroy -var-file=<env>.tfvarsTerraform & HelmDestroy everythingDestructiveWhat each part does
destroydelete all resources in this state (asks to confirm)-var-filesame variables as for apply
terraform apply -refresh-onlyTerraform & HelmSync state with reality without changing anythingCautionWhat each part does
-refresh-onlyupdate state from the real infrastructure (drift), no resource changes; replaces terraform refresh
terraform consoleTerraform & HelmTry expressions interactivelyWhat each part does
consoleREPL to evaluate expressions, functions and values from state, e.g. cidrsubnet("10.0.0.0/16", 8, 1)
terraform output -json | jqTerraform & HelmOutputs as JSONWhat each part does
output -jsonevery output with type and sensitive flag| jqpretty-print or pick values
terraform show -json tfplan | jq '.resource_changes[] | {address, actions: .change.actions}'Terraform & HelmShow a saved plan or state in JSONWhat each part does
show -json tfplanmachine-readable planjq '...'list each resource and its actions (create, update, delete)
terraform state pull > state-backup.tfstateTerraform & HelmDownload / back up the remote stateWhat each part does
state pullprint the current remote state> filesave a copy before risky state surgery
terraform providers; terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64Terraform & HelmProviders and lock file for all platformsWhat each part does
providersprovider requirements per moduleproviders lock -platform=...record checksums for every OS your team and CI use
terraform versionTerraform & HelmVersions of Terraform and providersWhat each part does
versionTerraform version and the provider versions selected in this directory
terraform graph | dot -Tsvg > graph.svgTerraform & HelmDependency graphWhat each part does
graphresource dependencies in DOT formatdot -Tsvgrender with Graphviz
terraform testTerraform & HelmRun Terraform testsWhat each part does
testrun *.tftest.hcl files: plan/apply assertions against your module
terraform init -upgrade -backend=falseTerraform & HelmUnlock a provider upgrade in one moduleWhat each part does
-upgradenewest allowed provider versions-backend=falsedon't touch the backend (fast, for local checks)
helm repo add <name> <url> && helm repo updateTerraform & HelmAdd a chart repo and refreshWhat each part does
repo add <name> <url>register a chart repositoryrepo updaterefresh the local index of all repos
helm show values <repo>/<chart> > values.yamlTerraform & HelmLook at a chart's default valuesWhat each part does
show valuesprint the chart's values.yaml> values.yamlsave it as a starting point
helm template <release> <chart> -f <values-file> | lessTerraform & HelmRender templates locally (no cluster)What each part does
templaterender manifests locally-f <values-file>your values (repeatable; later files win)| lesspage through the output
helm upgrade --install <release> <chart> -n <namespace> --create-namespace -f <values-file> --set <key>=<value> --wait --timeout 5mTerraform & HelmInstall or upgrade in one commandWhat each part does
upgrade --installupgrade if the release exists, otherwise install (-i)-n <namespace>target namespace--create-namespacecreate it if missing (with --install)-f <values-file>values file--set <key>=<value>override one value on the command line (wins over -f)--waitwait until resources are ready--timeout 5mhow long to wait
helm upgrade --install <release> <chart> --rollback-on-failure --timeout 5mTerraform & HelmRoll back automatically if the upgrade failsWhat each part does
--rollback-on-failureHelm 4: on failure, roll back to the last good release (implies --wait)
Tip Helm 3 calls this flag --atomic.
Terraform & Helm cheat sheet →helm history <release> -n <namespace>; helm rollback <release> <revision> -n <namespace>Terraform & HelmRelease history and rollbackCautionWhat each part does
historyrevisions with status and chart/app versionsrollback <release> <revision>return to that revision (omit it for the previous one)
helm list -A | grep <release>Terraform & HelmFind a release in any namespaceWhat each part does
list -Areleases in all namespaces| grep <release>keep the matching row
helm get values <release> -n <namespace> --allTerraform & HelmValues actually used by a releaseWhat each part does
get valuesuser-supplied values of the deployed release--allinclude chart defaults too
helm uninstall <release> -n <namespace>Terraform & HelmRemove a releaseDestructiveWhat each part does
uninstalldelete all resources of the release (PVCs may stay)
helm search repo <keyword> --versions; helm search hub <keyword>Terraform & HelmSearch charts in added repos / Artifact HubWhat each part does
search repocharts in your added repos--versionsevery chart version, not only the latestsearch hubsearch Artifact Hub
helm pull <repo>/<chart> --version <version> --untarTerraform & HelmDownload and unpack a chartWhat each part does
pulldownload the chart .tgz--versionspecific chart version--untarunpack to a folder to read templates
helm show chart <repo>/<chart>; helm show readme <repo>/<chart>Terraform & HelmShow a chart's metadata and READMEWhat each part does
show chartChart.yaml: version, appVersion, dependenciesshow readmedocumentation
helm upgrade --install <release> oci://<registry>/<path>/<chart> --version <version> -n <namespace>Terraform & HelmInstall a chart from an OCI registryWhat each part does
oci://...charts stored in a container registry (no helm repo add)--versionchart version
helm status <release> -n <namespace>Terraform & HelmStatus and notes of a releaseWhat each part does
statusdeployed / failed / pending-upgrade, revision, and the chart's NOTES
helm get manifest <release> -n <namespace>Terraform & HelmWhat did Helm actually deploy?What each part does
get manifestthe rendered YAML of the current revision (--revision <n> for older)
helm list -A --pending --failedTerraform & HelmReleases stuck or failedWhat each part does
-Aall namespaces--pending --failedonly releases in those states (pending-upgrade blocks new upgrades)
helm upgrade <release> <chart> -f <values-file> --dry-run=server --debug -n <namespace>Terraform & HelmPreview an upgrade without applyingWhat each part does
--dry-run=serverrender and validate against the cluster, change nothing--debugprint the rendered manifests
helm diff upgrade <release> <chart> -f <values-file> -n <namespace>Terraform & HelmDiff an upgrade (helm-diff plugin)What each part does
helm diff upgradecolored diff between the live release and what the upgrade would deploy (helm plugin install https://github.com/databus23/helm-diff)
helm upgrade <release> <chart> --reuse-values --set <key>=<value>Terraform & HelmKeep current values on upgradeCautionWhat each part does
--reuse-valuesstart from the last release's values--setchange only this one
Tip Can hide new chart defaults; --reset-then-reuse-values is safer on Helm 3.14+.
Terraform & Helm cheat sheet →helm create <chart>Terraform & HelmCreate a new chartWhat each part does
helm createscaffold a chart: Chart.yaml, values.yaml, templates
helm lint <chart-dir> -f <values-file>Terraform & HelmLint a chartWhat each part does
lintcheck the chart and rendered templates for errors and best practices
helm dependency update <chart-dir>Terraform & HelmFetch chart dependenciesWhat each part does
dependency updatedownload the subcharts listed in Chart.yaml into charts/ and update Chart.lock
helm package <chart-dir> && helm push <chart>-<version>.tgz oci://<registry>/<path>Terraform & HelmPackage and push a chart to an OCI registryWhat each part does
packagebuild <chart>-<version>.tgzpush ... oci://upload to the registry (helm registry login first)
helm test <release> -n <namespace>Terraform & HelmRun a release's testsWhat each part does
helm testrun the chart's test hook pods and report pass/fail
helm plugin listTerraform & HelmInstalled Helm plugins
Context, config, volumes & state45
docker volume ls; docker volume create <name>; docker volume rm <name>DockerList / create / remove volumesCautionWhat each part does
volume lsnamed volumes (persistent data)volume create <name>create one (docker run -v <name>:/path also creates it)volume rm <name>delete it and its data
docker run -d -v <volume>:<container-path> <image>DockerMount a named volume into a containerWhat each part does
-v <volume>:<container-path>data written to <container-path> survives container removal
docker network ls; docker network create <name>DockerList / create networksWhat each part does
network lsbridge, host, none + your own networksnetwork create <name>user-defined bridge: containers on it reach each other by name
docker run -d --name <name> --network <network> <image>DockerRun a container on a networkWhat each part does
--network <network>attach to that network; other containers can reach it as http://<name>
docker volume inspect <volume>; docker ps -a --filter volume=<volume>DockerWhere is a volume's data and who uses it?What each part does
docker volume inspectdriver, mountpoint on the host, labelsdocker ps -a --filter volume=<volume>containers using it
docker run --rm -v <volume>:/data:ro -v "$PWD":/backup alpine tar czf /backup/<volume>.tgz -C /data .DockerBack up a volume to a tar fileWhat each part does
docker run --rmthrowaway helper container-v <volume>:/data:romount the volume read-only-v "$PWD":/backupmount the current host folderalpine tar czf ... -C /data .archive the volume contents into the host folder
Tip Stop the app first (or use its own dump tool) for consistent database backups.
Docker cheat sheet →docker run --rm -v <volume>:/data -v "$PWD":/backup alpine tar xzf /backup/<volume>.tgz -C /dataDockerRestore a volume from a tar fileCautionWhat each part does
-v <volume>:/datamount the target volume read-writetar xzf ... -C /dataunpack the backup into it
docker volume prune -aDockerRemove unused volumesDestructiveWhat each part does
docker volume prunedelete volumes no container uses-ainclude named volumes (without it, only anonymous ones on Docker 23+)
docker network inspect <network> --format '{{json .IPAM.Config}} {{range .Containers}}{{.Name}} {{.IPv4Address}}; {{end}}'DockerInspect a network: subnet and connected containersWhat each part does
docker network inspect <network>network details{{json .IPAM.Config}}subnet and gateway{{range .Containers}}...{{end}}each attached container with its IP
docker network connect <network> <container>; docker network disconnect <network> <container>DockerConnect / disconnect a running container to a networkWhat each part does
docker network connectattach to another network (containers can be on several)docker network disconnectdetach
docker run --rm --network host <image>; docker run --rm --network none <image>DockerRun with host or no networkingWhat each part does
--network hostshare the host's network stack: no port mapping, no isolation (Linux only)--network noneno network at all, only loopback
docker network prune -fDockerRemove unused networksCautionWhat each part does
docker network prunedelete networks no container uses-fno prompt
docker context create <name> --docker host=ssh://<user>@<host>; docker context use <name>DockerRun docker commands against a remote hostWhat each part does
docker context createsave a named connection to another Docker daemon--docker host=ssh://<user>@<host>connect over SSH (no exposed TCP port needed)docker context use <name>make it the default; docker context use default to come back
DOCKER_HOST=ssh://<user>@<host> docker psDockerOne-off command on a remote daemonWhat each part does
DOCKER_HOST=ssh://...point this one command at another daemondocker psany docker command
cat /etc/docker/daemon.json; journalctl -u docker -n 100 --no-pagerDockerCheck the daemon config and its logsWhat each part does
/etc/docker/daemon.jsondaemon settings: log driver and rotation, registry mirrors, data-root, address poolsjournalctl -u dockerthe daemon's own logs (start errors, pull failures)
docker info --format '{{.DockerRootDir}} {{.Driver}} {{.LoggingDriver}} {{.CgroupDriver}}'DockerWhere does Docker store its data?What each part does
{{.DockerRootDir}}data directory, usually /var/lib/docker{{.Driver}}storage driver (overlay2){{.LoggingDriver}}default log driver (json-file, local, journald){{.CgroupDriver}}systemd or cgroupfs
kubectl config current-contextKubernetesWhich cluster am I talking to?What each part does
kubectl configwork with the kubeconfig filecurrent-contextprint the active context (cluster + user + default namespace)
kubectl config get-contexts; kubectl config use-context <context>KubernetesList contexts and switchWhat each part does
get-contextsall contexts; * marks the active oneuse-context <context>make <context> the default for later commands
Tip Check twice before running anything against prod.
Kubernetes cheat sheet →kubectl config set-context --current --namespace=<namespace>KubernetesSet the default namespace for this contextWhat each part does
set-contextedit a context--currentthe active one--namespace=<namespace>saved default namespace, so you can drop -n afterwards
kubectl exec <pod> -n <namespace> -- envKubernetesPrint env vars of a running podWhat each part does
kubectl exec <pod>run in the pod (add -c <container>)-n <namespace>in this namespace (default: the context's namespace; -A for all)-- envprint all environment variables
kubectl set env deploy/<deployment> --list -n <namespace>KubernetesEnv vars set on a deployment (incl. from ConfigMaps/Secrets)What each part does
set env ... --listlist the env defined in the pod template, showing which come from configMapKeyRef / secretKeyRef-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl set env deploy/<deployment> <KEY>=<value> -n <namespace>; kubectl set env deploy/<deployment> <KEY>- -n <namespace>KubernetesSet or remove an env var (triggers a rollout)CautionWhat each part does
<KEY>=<value>add or change<KEY>-trailing minus removes it
kubectl create configmap <name> --from-literal=<key>=<value> --from-file=<path> -n <namespace>KubernetesCreate a ConfigMap from literals or a fileWhat each part does
create configmap <name>new ConfigMap--from-literal=<key>=<value>one key/value--from-file=<path>file content (key = file name), or a whole directory
kubectl create secret generic <name> --from-literal=<key>=<value> -n <namespace>KubernetesCreate a generic secretWhat each part does
secret genericOpaque secret--from-literalvalue from the command line (lands in shell history: prefer --from-file or --from-env-file)
kubectl create secret docker-registry <name> --docker-server=<registry> --docker-username=<user> --docker-password=<token> -n <namespace>KubernetesCreate an image pull secretWhat each part does
secret docker-registrycredentials for a private registry; reference it in imagePullSecrets
kubectl create secret tls <name> --cert=<cert>.pem --key=<key>.pem -n <namespace>KubernetesCreate a TLS secretWhat each part does
secret tlskubernetes.io/tls secret used by ingresses--cert / --keyPEM certificate (with chain) and private key
kubectl get secret <secret> -n <namespace> -o go-template='{{range $k,$v := .data}}{{$k}}={{$v | base64decode}}{{"\n"}}{{end}}'KubernetesDecode all keys of a secretWhat each part does
-o go-template='...'loop over every key and base64-decode the value
Tip Prints secrets in clear text on your screen.
Kubernetes cheat sheet →kubectl create configmap <name> --from-file=<path> --dry-run=client -o yaml | kubectl apply -f -KubernetesUpdate a ConfigMap from a file (apply-style)What each part does
--dry-run=client -o yamlgenerate the manifest without creating| kubectl apply -f -create or update it
Tip Pods only see new values after a restart (env) or after the kubelet syncs (mounted files).
Kubernetes cheat sheet →alias k=kubectl; source <(kubectl completion bash); complete -o default -F __start_kubectl kKubernetesShort alias with completion (bash)What each part does
alias k=kubectltype k get po instead of kubectl get podskubectl completion bashtab completion for resources and names (zsh: completion zsh)complete ... kmake completion work for the alias too
Tip PowerShell: Set-Alias -Name k -Value kubectl. Put these in ~/.bashrc to keep them.
Kubernetes cheat sheet →kubectl config get-clusters; kubectl config get-usersKubernetesList clusters and users in kubeconfigkubectl config view --minifyKubernetesShow the current context's config onlyWhat each part does
config viewkubeconfig contents (secrets redacted)--minifyonly what the current context uses
KUBECONFIG=~/.kube/config:<other-config> kubectl config view --flatten > merged-configKubernetesMerge several kubeconfig filesWhat each part does
KUBECONFIG=a:bcolon-separated list of files kubectl reads togetherview --flattenone self-contained file
kubectl config delete-context <context>KubernetesRemove a contextWhat each part does
delete-contextremove it from kubeconfig (cluster and user entries stay)
kubectx <context>; kubens <namespace>KubernetesSwitch context / namespace quicklyWhat each part does
kubectxswitch context (plugin)kubensswitch default namespace
kubectl explain pod.spec.containers --recursive | lessKubernetesExplain every field of a resourceWhat each part does
explain <path>docs for a field--recursivethe whole tree of sub-fields
kubectl get po -A --sort-by=.metadata.creationTimestampKubernetesSort outputWhat each part does
--sort-by=<jsonpath>sort by any field: creation time, .status.startTime, restartCount...
kubectl plugin list; kubectl krew listKubernetesList kubectl pluginsWhat each part does
plugin listkubectl-* binaries on your PATHkrew listplugins installed with the krew plugin manager
kubectl attach -it <pod> -c <container>KubernetesAttach to a running containerWhat each part does
attachconnect to the main process's stdin/stdout (exec starts a new process instead)
kubectl get po -v=6KubernetesShow more detail about what kubectl doesWhat each part does
-v=6log the API calls kubectl makes (8 includes bodies): useful for auth and timeout problems
terraform state list | grep <name>Terraform & HelmFind a resource in stateWhat each part does
state listevery resource address in the state| grep <name>keep matching addresses
terraform state show <address>Terraform & HelmInspect one resourceWhat each part does
state show <address>all attributes stored for that resource
terraform state mv <old-address> <new-address>Terraform & HelmRename/move without destroyingCautionWhat each part does
state mvchange the address in state (e.g. after refactoring into a module)
Tip Newer alternative: a moved {} block in code.
Terraform & Helm cheat sheet →terraform state rm <address>Terraform & HelmStop managing a resource (keep it in the cloud)CautionWhat each part does
state rmforget the resource; the real object is NOT deleted
terraform output -raw <name>Terraform & HelmRead an output for scriptsWhat each part does
output <name>print an output value-rawplain string without quotes (for shell variables)
terraform force-unlock <lock-id>Terraform & HelmRelease a stuck lockDestructiveWhat each part does
force-unlock <lock-id>remove a lock left by a crashed run (ID is in the error message)
Tip Make sure nothing else is running against this state.
Terraform & Helm cheat sheet →
History, branches & undo48
git log --oneline --graph --decorate --allGitCompact graph of all branchesWhat each part does
git logshow commit history--onelineone line per commit: short hash + subject--graphASCII graph of branches and merges--decorateshow branch and tag names next to commits--allinclude every branch and tag, not just the current one
git log --oneline | grep -i <text>GitFind commits whose message mentions somethingWhat each part does
git log --onelineone commit per line| grep -i <text>keep lines containing <text>, any case
Tip Built-in: git log --oneline --grep=<text> -i
Git cheat sheet →git log --oneline --author=<name> --since=<date> --until=<date>GitCommits by someone in a date rangeWhat each part does
--author=<name>author matches (regex)--since / --untildate range, e.g. "2 weeks ago", 2026-11-01
git log -S"<text>" -pGitWhen was this string added or removed?What each part does
-S"<text>""pickaxe": commits that changed how many times <text> appears-pshow the diff of each matching commit
git log --follow -p -- <file>GitHistory of one file, across renamesWhat each part does
--followkeep following the file when it was renamed-pwith diffs-- <file>"--" ends options; what follows is a path
git blame -L <start>,<end> -- <file>GitWho changed these linesWhat each part does
blamelast commit + author for every line-L <start>,<end>only that line range
git status -sb; git diff; git diff --stagedGitWhat is staged vs notWhat each part does
status -sbshort status with branch infogit diffunstaged changesgit diff --stagedwhat will go into the next commit
git restore --staged <file>GitUnstage a file (keep the changes)What each part does
restorerestore files--stagedonly the index (staging area): the change goes back to "not staged"
git restore <file>GitDiscard local changes to a fileDestructiveWhat each part does
restore <file>replace the working copy with the last committed/staged version
git reset --soft HEAD~1GitUndo the last commit, keep the changes stagedCautionWhat each part does
resetmove the current branch pointer--softonly move HEAD; index and files are untouchedHEAD~1one commit before HEAD
git fetch origin && git reset --hard origin/<branch>GitThrow away local commits and changes to match the remoteDestructiveWhat each part does
git fetch origindownload the latest remote state&&only if that workedreset --hardmove the branch AND overwrite index + working treeorigin/<branch>the remote version
git revert <commit>GitUndo a pushed commit safelyWhat each part does
revert <commit>create a new commit that undoes <commit>; history is not rewritten
git reflog -n 20GitFind a "lost" commitWhat each part does
reflogevery place HEAD has been (commits, resets, rebases)-n 20last 20 entries; then git branch rescue <sha>
git stash push -u -m "<message>"; git stash popGitPark work in progressWhat each part does
stash pushsave changes and clean the working tree-uinclude untracked files-m "<message>"label itstash popapply the latest stash and drop it
git switch -c <branch>GitCreate and switch to a branchgit branch --merged main | grep -vE '^\*|main' | xargs -r git branch -dGitDelete local branches already merged into mainCautionWhat each part does
git branch --merged mainbranches fully merged into maingrep -vE '^\*|main'-v: drop lines matching; -E: extended regex: the current branch (starts with *) and main itselfxargs -r git branch -ddelete each remaining branch; -d refuses unmerged ones
git fetch --pruneGitRemove stale remote-tracking branchesWhat each part does
fetchdownload from the remote--prunedelete local refs to branches that no longer exist on the remote
git pull --rebase origin mainGitRebase your branch on the latest mainWhat each part does
pullfetch + integrate--rebasereplay your commits on top instead of creating a merge commitorigin mainremote and branch
git push -u origin <branch>GitPush a new branch and track itgit push --force-with-lease origin <branch>GitForce-push safely after a rebaseCautionWhat each part does
--force-with-leaseoverwrite the remote branch only if nobody pushed since your last fetch
git push origin --delete <branch>GitDelete a remote branchDestructivegit cherry-pick <commit>GitCopy one commit onto the current branchWhat each part does
cherry-pick <commit>apply the changes of <commit> as a new commit here
git tag -a <version> -m "<message>" && git push origin <version>GitTag a release and push itWhat each part does
tag -a <version>annotated tag (has author, date, message)-m "<message>"tag messagegit push origin <version>tags are not pushed with branches; push it explicitly
git clean -nd; git clean -fdGitPreview / remove untracked filesDestructiveWhat each part does
cleanremove untracked files-ndry run: list what would be removed-dinclude untracked directories-factually delete
git rebase -i HEAD~<n>GitClean up your last commits before a PRCautionWhat each part does
rebase -iinteractive: reorder, squash (s), fixup (f), reword (r) or drop commitsHEAD~<n>the last n commits
Tip Rewrites history: only for commits not yet shared, or push with --force-with-lease.
Git cheat sheet →git fetch origin && git rebase origin/mainGitRebase your branch on the latest mainCautionWhat each part does
git fetch originget the newest maingit rebase origin/mainreplay your commits on top of it
git rebase --continue; git rebase --abort; git merge --abortGitContinue, skip or abort a rebase / mergeWhat each part does
--continueafter fixing conflicts and git addrebase --abortgo back to before the rebasemerge --abortcancel a conflicted merge
git commit --fixup <commit> && git rebase -i --autosquash <commit>~1GitSquash a fix into an earlier commit automaticallyCautionWhat each part does
commit --fixup <commit>commit marked fixup! for that commitrebase -i --autosquashmoves and squashes it into place
git bisect start <bad> <good>; git bisect good; git bisect bad; git bisect resetGitFind the commit that introduced a bugWhat each part does
bisect start <bad> <good>binary search between a bad commit (e.g. HEAD) and a known good onebisect good / badmark each checked-out commit after testingbisect resetfinish and return to your branch
Tip git bisect run <test-script> automates it.
Git cheat sheet →git log --oneline main..<branch>GitCommits on a branch that aren't on maingit diff main...<branch> --statGitCompare two branchesWhat each part does
main...<branch>changes on branch since it split from main (three dots)--statfiles and line counts only
git shortlog -sn --no-mergesGitWho committed how muchWhat each part does
shortlog -s -ncommit count per author, sorted--no-mergesskip merge commits
git grep -n '<text>' <commit-or-branch>GitSearch the code in any commitWhat each part does
git grep -nfast search of tracked files with line numbers<commit-or-branch>search that version instead of the working tree
git restore --source=<commit> -- <file>GitRestore a file from another commit or branchCautionWhat each part does
--source=<commit>take the file's content from that commit-- <file>only that path
git describe --tags --alwaysGitDescribe the current version from tagsWhat each part does
describe --tagsnearest tag + commits since + short SHA, e.g. v1.4.0-3-g4f2a9c1--alwaysfall back to the SHA if no tag
git filter-repo --invert-paths --path <file>GitRemove a file from all history (leaked secret)DestructiveWhat each part does
git filter-reporewrite the whole history (separate tool, replaces filter-branch)--invert-paths --path <file>drop that file everywhere
Tip Rotate the secret first; everyone must re-clone after the force push.
Git cheat sheet →git stash list; git stash show -p stash@{1}; git stash apply stash@{1}; git stash drop stash@{1}GitList, show, apply and drop stashesWhat each part does
stash listall stashesshow -pthe diff of oneapplyre-apply but keep it (pop removes it)dropdelete it
git tag -l 'v1.*'; git tag -d <tag> && git push origin --delete <tag>GitList and delete tagsCautionWhat each part does
tag -l 'v1.*'list matching tagstag -ddelete locallypush origin --delete <tag>delete on the remote
git push --tagsGitPush all tagsWhat each part does
--tagspush every local tag (git push --follow-tags pushes only annotated ones for pushed commits)
git remote set-url origin <url>GitChange a remote's URL (HTTPS to SSH, moved repo)git worktree add ../<dir> <branch>; git worktree list; git worktree remove ../<dir>GitWork on two branches at onceWhat each part does
worktree addcheck out another branch in a second folder, sharing the same repolist / removesee and clean up worktrees
git clone --recurse-submodules <url>; git submodule update --init --recursiveGitClone with submodules / update themWhat each part does
--recurse-submodulesalso clone nested repossubmodule update --init --recursivefetch submodules in an existing clone
git ls-files | grep <pattern>GitWhich files does git track?git check-ignore -v <file>GitWhy is this file ignored?git config --list --show-originGitSee all config and where it comes fromWhat each part does
--listevery setting--show-originwhich file set it (system, global, repo)
git config --global alias.lg "log --oneline --graph --decorate --all"GitCreate a git aliasgit archive --format=zip -o <file>.zip <commit-or-tag>GitMake a zip of a commit without .gitWhat each part does
git archiveexport the tracked files of that version--format=zip -ooutput format and file
git switch -GitSwitch back to the previous branch
Clean up16
docker system dfDockerHow much space Docker usesWhat each part does
docker system dfspace used by images, containers, volumes and build cache, plus how much is reclaimable
docker ps -q | xargs -r docker stopDockerStop all running containersCautionWhat each part does
docker ps -qIDs of running containers|pipe them to xargsxargs -rpass them as arguments; -r: don't run if the list is emptydocker stopstop each one gracefully (SIGTERM, then SIGKILL after 10s)
docker ps -aq --filter status=exited | xargs -r docker rmDockerRemove all exited containersCautionWhat each part does
-aqall containers, IDs only--filter status=exitedonly exited onesxargs -r docker rmremove them
Tip Same result: docker container prune
Docker cheat sheet →docker system prune -f --filter "until=24h"DockerRemove unused data older than a dayCautionWhat each part does
docker system pruneremove stopped containers, unused networks, dangling images and build cache-f--force: no confirmation prompt--filter "until=24h"only things older than 24 hours
docker system prune -a --volumesDockerRemove everything unused, including volumesDestructiveWhat each part does
-a--all: also every image not used by a container (not just dangling)--volumesalso unused volumes: this deletes data
docker builder prune -af --filter "until=24h"DockerRemove build cache onlyCautionWhat each part does
docker builder pruneremove BuildKit build cache (image prune does not touch it)-aall cache, not only dangling-fno prompt--filter "until=24h"keep the last day of cache
kubectl delete pods -n <namespace> --field-selector=status.phase=FailedKubernetesDelete failed / evicted podsDestructiveWhat each part does
delete podsdelete pods…--field-selector=status.phase=Failed…but only those in phase Failed (includes Evicted)
kubectl get pods -n <namespace> --no-headers | awk '/<pattern>/{print $1}' | xargs -r kubectl delete pod -n <namespace>KubernetesDelete pods whose name matches a patternDestructiveWhat each part does
--no-headersdrop the header row so only data lines go throughawk '/<pattern>/{print $1}'for lines matching <pattern>, print column 1 (the pod name)xargs -r kubectl delete poddelete each name; -r: skip if nothing matched
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data; kubectl uncordon <node>KubernetesTake a node out for maintenance and backCautionWhat each part does
drain <node>cordon the node and evict its pods--ignore-daemonsetsdon't fail on DaemonSet pods (they stay)--delete-emptydir-dataallow evicting pods that use emptyDir (that data is lost)uncordon <node>make it schedulable again
kubectl top node; kubectl describe node <node>KubernetesNode usage and detailsWhat each part does
top nodeCPU/memory per nodedescribe nodecapacity, allocatable, conditions (DiskPressure, MemoryPressure) and pods on it
kubectl delete po <pod> -n <namespace>KubernetesDelete a pod (its controller recreates it)CautionWhat each part does
delete po <pod>graceful delete; a Deployment/StatefulSet makes a new one-n <namespace>in this namespace (default: the context's namespace; -A for all)
kubectl delete po <pod> -n <namespace> --grace-period=0 --forceKubernetesForce delete a stuck podDestructiveWhat each part does
--grace-period=0 --forceremove from the API immediately without waiting for the kubelet (pod stuck in Terminating)
Tip The container may still be running on the node; for StatefulSets this can cause two pods with the same identity.
Kubernetes cheat sheet →kubectl delete po,svc -l app=<app> -n <namespace>KubernetesDelete by labelDestructiveWhat each part does
po,svcseveral types at once-l app=<app>everything with that label
kubectl delete <type> <name> -n <namespace>KubernetesDelete a resource by type and nameDestructiveWhat each part does
<type> <name>e.g. deploy api, svc api, cm app-config, rs api-7d9f
kubectl delete all --all -n <namespace>KubernetesDelete everything in a namespace (keep the namespace)DestructiveWhat each part does
allpods, services, deployments, replicasets, statefulsets, jobs (not configmaps, secrets, PVCs)--allevery object of those types
kubectl delete ns <namespace>KubernetesDelete a namespace and everything in itDestructiveWhat each part does
delete nsremoves the namespace and all objects in it, including PVCs and secrets
Nothing matches.
My DevOps Playbook by Angelo John Calleja