Linux

Commands for DevOps — from the basics to Kubernetes.

Examples use Bash on Linux. Replace placeholders such as FILE, USER, and NAMESPACE with your values. Some tools need installing first; apt and dnf belong to different distributions. Rows are individual examples, not a script to run from start to finish.

Help and command discovery

CommandExplanation
man COMMANDOpens the command's manual, including options and examples. Search with /TEXT, jump to the next match with n, and quit with q.
man -k KEYWORDSearches manual-page names and short descriptions for a keyword; useful when you know the task but not the command.
help cdShows Bash's own help for the cd builtin. Builtins run inside the shell and may behave differently from similarly named external programs.
COMMAND --helpPrints a quick usage summary for commands that support --help, including their accepted flags and arguments.
type -a COMMANDShows how Bash resolves a command name, including aliases, functions, builtins and matching executables. -a lists all matches instead of only the first.
command -v COMMANDReports what Bash would execute for this name and returns a nonzero status if it cannot find it. Useful for checking whether a required tool is available.

Navigate directories

CommandExplanation
pwdPrints the current working directory as an absolute path. Relative paths in subsequent commands start from this directory.
ls -lahLists the current directory: -l shows permissions, owner, size and time; -a includes hidden names beginning with a dot; -h makes sizes easier to read.
cd DIRECTORYChanges the current directory; a path beginning with / is absolute, otherwise it is relative to your current location. Quote paths containing spaces, for example cd 'My Projects'.
cd ..Moves to the parent directory. A single dot (.) means the current directory, while two dots (..) mean its parent.
cd ~Returns to your home directory; Bash expands an unquoted ~ to your home path. cd without an argument does the same.
cd -Returns to the previous working directory and prints its path. Repeating it switches between the last two locations.

Read file contents

CommandExplanation
cat FILEWrites the whole file to standard output. With several filenames, cat prints their contents consecutively in the supplied order.
less FILEOpens a file in a scrollable viewer without editing it. Search with /TEXT, continue with n, and exit with q.
head -n 20 FILEPrints the first 20 lines; -n selects a line count. Useful for inspecting a file's header or the beginning of a large result.
tail -n 50 FILEPrints the last 50 lines. Add -F to keep following a log by filename even when the file is replaced during rotation.

Edit files and keep terminal sessions

CommandExplanation
nano FILEOpens a file in the nano editor, where you can type immediately. Save with Ctrl+O then Enter, and exit with Ctrl+X; saving writes your changes to the file.
vim FILEOpens a file in Vim; press i to enter insert mode and edit, then Esc to return to normal mode. Enter :wq to save and quit, or :q! to discard unsaved changes and quit, confirming either command with Enter.
tmux new -s SESSIONStarts a named tmux session whose terminal programs can keep running after you detach or lose the client connection. The session lives on this host and does not survive its reboot.
tmux detachDetaches the current tmux client while leaving the session and its programs running. The default keyboard shortcut inside tmux is Ctrl+B followed by d.
tmux attach -t SESSIONReconnects to an existing named session on this host. Use tmux ls to see available sessions before choosing the target with -t.

Find files and text

CommandExplanation
find DIRECTORY -type f -name '*.log'Recursively finds regular files whose names end in .log. Quotes keep Bash from expanding the wildcard before find receives it; -iname ignores letter case.
find DIRECTORY -type f -mtime -1Finds regular files modified within the last 24 hours. -mtime counts elapsed 24-hour periods, not calendar days.
find DIRECTORY -type f -name '*.conf' -exec grep -nH -- 'PATTERN' {} +Searches matching configuration files and prints filenames plus line numbers. {} supplies filenames directly to grep, and + batches them while preserving names containing spaces.
grep -n -- 'PATTERN' FILEPrints lines matching a basic regular expression, with their line numbers. -- ends option parsing so a pattern beginning with a hyphen is treated as data.
grep -rIn -- 'PATTERN' DIRECTORYSearches text files recursively: -r descends into directories, -I skips binary files and -n prints line numbers. Unlike -R, -r does not follow symbolic links encountered inside the tree.
grep -F -- 'TEXT' FILESearches for literal text instead of a regular expression. Characters such as dots and brackets match themselves, which is useful for exact fragments of logs or configuration.
grep -E -- 'error|warning' FILEMatches lines containing error or warning using an extended regular expression. -E enables operators such as | for alternatives and + for one or more repetitions.
grep -vE -- '^[[:space:]]*(#|$)' FILEPrints lines that are neither blank nor comments beginning with #, allowing leading whitespace. -v reverses the match; it does not remove inline comments.
grep -n -B 2 -A 3 -- 'PATTERN' FILEShows each matching line with two lines before it and three after it. -B means before, -A means after, and -C uses the same count on both sides.
rg -n 'PATTERN' DIRECTORYSearch file contents recursively with ripgrep, showing line numbers. It normally respects ignore files and skips hidden and binary files; install rg separately if missing.
find DIRECTORY -type f -name '*.log' -print0 | xargs -0 -r wc -lPass found filenames to wc safely even when names contain spaces or newlines. GNU xargs -r avoids running wc when there are no matches.

Transform and summarize text

CommandExplanation
sort -n FILESorts lines by their leading numeric value rather than alphabetically, so 2 comes before 10. Add -r for descending order; the input file is unchanged.
sort FILE | uniq -c | sort -nrCounts identical lines and places the most frequent first. uniq only combines adjacent duplicates, so the initial sort is necessary for unsorted input.
cut -d ':' -f 1 FILEExtracts the first field from each colon-separated line. -d chooses the separator and -f chooses fields; cut does not understand CSV quoting rules.
awk -F ':' '{print $1, $3}' FILEPrints the first and third colon-separated fields from every line. Single quotes protect awk's $1 and $3 from Bash variable expansion.
sed -n '10,20p' FILEPrints only lines 10 through 20. -n suppresses sed's normal output, and p explicitly prints the selected range.
sed 's/OLD/NEW/g' FILEPrints a version with every match of the OLD regular expression replaced by NEW; g replaces all matches per line. The source file is unchanged, and special characters in the pattern or replacement need escaping.
wc -l FILECounts newline characters, usually corresponding to the number of text lines. Use -w for words, -c for bytes or -m for characters.
LC_ALL=C tr '[:lower:]' '[:upper:]' < FILEConverts lowercase ASCII letters to uppercase without changing FILE; LC_ALL=C makes this command use the C locale. GNU tr does not provide full Unicode case conversion.
diff -u OLD_FILE NEW_FILECompare two text files using unified diff format. Exit status 1 means differences exist; it does not mean the comparison failed.
base64 FILEEncode file bytes as printable Base64 text; this is encoding, not encryption. GNU base64 wraps output lines unless -w 0 is added.
base64 --decode FILEDecode Base64 text to its original bytes on standard output. Redirect binary output to a file rather than displaying it in the terminal.

Work with JSON and YAML

CommandExplanation
jq '.' FILE.jsonParses JSON and prints it with readable indentation; invalid JSON produces an error. jq works with JSON structure rather than matching text lines.
jq -r '.metadata.name' FILE.jsonReads the nested metadata.name value. -r prints string results without JSON quotes, making them suitable as input to another command.
jq '.items[] | select(.enabled == true)' FILE.jsonIterates over the items array and prints only objects whose enabled field is true. This pipe belongs to jq's expression, so the entire filter stays inside single quotes.
jq --arg name 'NAME' '.items[] | select(.name == $name)' FILE.jsonPasses a string into a jq filter without constructing filter code from the value. --arg creates a string variable; --argjson is for an already valid JSON value.
yq eval '.metadata.name' FILE.yamlReads a YAML field using Mike Farah's yq v4, which uses jq-like expressions but is a separate tool. Other programs named yq have different options and behavior.
yq eval -i '.spec.replicas = 3' FILE.yamlUpdates spec.replicas in the YAML file using Mike Farah's yq v4. -i writes the result back to the same file; omit -i to preview the result on standard output.

Streams, pipes and redirection

CommandExplanation
COMMAND > FILERedirects standard output (stream 1) into a file, creating it or truncating its existing contents before the command runs. Error output still goes to the terminal.
COMMAND >> FILEAppends standard output to the end of a file instead of replacing its contents. Creates the file if it does not exist.
COMMAND 2> ERRORS.logRedirects standard error (stream 2) into a file, replacing any existing contents. Normal output still goes to the terminal.
COMMAND > OUTPUT.log 2>&1Sends both standard output and standard error to one file. Order matters: 2>&1 copies standard output's destination after > has redirected it.
COMMAND < FILESupplies a file as standard input (stream 0) instead of reading from the keyboard. The command must support reading its input from that stream.
grep -F -- 'TEXT' FILE | wc -lConnects grep's standard output to wc's standard input to count matching lines. A normal pipe carries standard output only, so error messages are not included.
COMMAND | tee -a OUTPUT.logShows standard output in the terminal and appends a copy to a file. Without -a, tee replaces the file's contents; errors from COMMAND bypass this pipe.
printf '%s\n' 'TEXT' | sudo tee FILE > /dev/nullWrites text to a file with administrator privileges, replacing its contents, while hiding tee's duplicate output. sudo controls tee's file access; sudo COMMAND > FILE would still have your current shell open FILE.

Permissions, users and groups

CommandExplanation
idShows your user ID, primary group ID and supplementary groups. Add a username to inspect another account instead of the current session's identity.
getent passwd USERLooks up an account through the system's configured identity sources, including local files or a directory service. Shows fields such as UID, home directory and login shell, not the user's password.
chmod u+x SCRIPTAdds execute permission for the file's owner while preserving other permission bits. u means owner, g means group and o means others.
chmod 640 FILESets owner permissions to read/write, group to read only and others to none. Each digit adds read (4), write (2) and execute (1) for owner, group and others in that order.
chmod 750 DIRECTORYGives the owner full directory access, the group listing and traversal rights, and others no access. On directories, r lists names, x allows traversal and w together with x permits adding or removing entries.
sudo chown USER:GROUP FILEChanges a file's owner and group. Without -R this affects only the named path, not the contents of a directory.
chgrp GROUP FILEChanges only the file's group. A file owner can normally choose one of their own groups; other changes require administrator privileges.
umask 077Masks group and other permissions for files and directories created afterward by this shell and its children. Typical results are 600 for files and 700 for directories; existing paths are unchanged.
sudo COMMANDRuns one command as root when your sudo policy permits it. Root is the administrator account; sudo may request your own password to authorize the action.
sudo -u USER COMMANDRuns a command as the specified account instead of root, subject to sudo policy. Useful for checking a service account's file access or running its maintenance command.
sudo useradd -m -s /bin/bash USERCreates a local account, creates its home directory with -m and sets Bash as its login shell with -s. Set a password or configure another login method separately.
sudo passwd USERSets or changes an account's password through an interactive prompt. With no username and without sudo, passwd changes your own password.
sudo groupadd GROUPCreates a local group for sharing permissions among accounts. Creating a group does not automatically add users to it.
sudo usermod -aG GROUP USERAdds an account to a supplementary group; -a appends, while -G alone replaces its supplementary-group list. Start a new login session to use the updated membership.
getfacl FILERead a file's access control list, including extra user or group permissions beyond the traditional owner/group/others bits. Requires ACL tools and filesystem support.
setfacl -m u:USER:r FILEGrant a named user read access through the file's ACL. The caller must own the file or have sufficient privilege; parent-directory traversal permissions still matter.

Bash variables and scripts

CommandExplanation
label='VALUE'; printf '%s\n' "$label"Assigns a shell variable without spaces around = and prints its value. Double quotes preserve spaces and prevent wildcard expansion in the expanded value.
printf '%s\n' '$label' "$label"Prints the literal text $label, then the variable's value. Single quotes suppress expansion; double quotes allow variable and command expansion while keeping each result together.
export APP_ENV='development'Makes APP_ENV available in the environment of programs started from this shell. A normal variable assignment alone does not export a new variable to child programs.
current_dir=$(pwd)Runs pwd and stores its standard output in a variable; command substitution removes trailing newlines. Read the value later as "$current_dir" to preserve spaces.
count=3; printf '%s\n' "$((count + 1))"Evaluates integer arithmetic in Bash and prints 4. $((...)) calculates a number, while $(...) captures a command's output.
printf '%s\n' "${APP_ENV:-development}"Uses development when APP_ENV is unset or empty, without assigning that default to the variable. The colon makes empty values count as missing too.
read -r -p 'Name: ' namePrompts for a line of input and stores it in name. -r keeps backslashes literal instead of treating them as escapes.
if [[ -f FILE ]]; then printf '%s\n' 'File exists'; fiRuns the body only if FILE exists and is a regular file. Bash's [[...]] supports tests such as -d for directories and -r for readability; spaces around the brackets are required.
mkdir -p DIRECTORY && cd DIRECTORYRuns cd only if mkdir succeeds with exit status 0. && chains commands whose next step depends on the previous step succeeding.
COMMAND || printf '%s\n' 'Command failed' >&2Prints a message to standard error only if COMMAND returns a nonzero status. The overall list then has printf's status, so use an explicit exit if the script must also fail.
for item in 'FILE_ONE' 'FILE_TWO'; do printf '%s\n' "$item"; doneRuns the loop body once for each supplied value. Quoting each value and "$item" keeps filenames containing spaces together.
while IFS= read -r line || [[ -n $line ]]; do printf '%s\n' "$line"; done < FILEReads a file one line at a time while preserving whitespace and backslashes. The extra test also processes a final line that lacks a newline character.
greet() { printf 'Hello, %s\n' "$1"; }; greet 'NAME'Defines a reusable shell function and calls it with one argument. Inside a function, $1 is its first argument and "$@" represents all arguments separately.
bash SCRIPT.sh ARGUMENTRuns a script in a new Bash process, with ARGUMENT available as $1. The script needs read permission but does not need its executable bit set for this invocation.
source FILE.shExecutes shell code in the current shell, so variable, function and directory changes remain afterward. Use it for files whose code you intend to run in your current session.
COMMAND; status=$?; printf 'Exit status: %s\n' "$status"Captures a command's exit status immediately: 0 usually means success, while nonzero values have command-specific meanings. Each later command replaces $?, which is why the value is saved first.
exit 1Ends the current script or shell with failure status 1; exit 0 reports success. In an interactive terminal this exits the current shell session.
set -o pipefailMakes a pipeline fail when any stage fails, using the rightmost nonzero status; normally only its last command determines the status. This does not itself stop a script; check the status or handle it explicitly.
printenv PATHPrint the PATH environment variable: a colon-separated list of directories searched for external commands.
env APP_ENV=test COMMANDRun one command with an environment variable override without changing the calling shell's environment.
unset APP_ENVRemove a shell variable and its exported value from the current shell's environment. Already running child processes keep their own environments.
alias ll='ls -lah'Define a shortcut in the current interactive Bash session. Put it in ~/.bashrc if it should also be defined in future interactive Bash sessions.
history 20Show the last 20 entries in the current Bash command history. Commands containing credentials can remain in history, so use interactive prompts or files for secrets.
bash -n SCRIPT.shCheck a script's Bash syntax without running its commands. This does not detect every logic or runtime error.
bash -x SCRIPT.shRun a script while printing commands after expansion for debugging. Expanded values can reveal secrets in the trace.
shellcheck SCRIPT.shStatically inspect a shell script for common bugs such as unsafe quoting and mistaken variable use. Requires ShellCheck; it does not execute the script.

Bash job control

CommandExplanation
COMMAND &Starts a command in the background so the shell can accept another command immediately. Its output still uses the terminal unless redirected; $! holds the latest background command's process ID.
jobs -lLists jobs belonging to the current shell, including their state and process IDs. Job numbers such as [1] are local to this shell and differ from system process IDs.
fg %1Brings job 1 into the foreground, resuming it if stopped. In an interactive shell, Ctrl+Z normally suspends a foreground job so you can manage it with jobs, bg or fg.
bg %1Resumes a stopped job in the background. Commands that need terminal input may stop again until brought to the foreground.
wait "$!"Waits for the most recently started background command and returns its exit status. Use it after starting a background command; wait without arguments waits for all active child jobs.

Archives, compression and checksums

CommandExplanation
tar -czf ARCHIVE.tar.gz DIRECTORYCreates a gzip-compressed archive of a directory: -c creates, -z compresses and -f names the archive file. An existing archive with that name is replaced; the source directory remains.
tar -tzf ARCHIVE.tar.gzLists archive entries without extracting them. -t lists contents; add -v to show details such as stored permissions and sizes.
tar -xzf ARCHIVE.tar.gz -C DIRECTORYExtracts an archive into an existing directory; -x means extract and -C selects the destination. Matching files can be replaced, so an empty destination keeps the extracted contents separate.
gzip -k FILECompresses one file into FILE.gz and keeps the original because of -k. gzip compresses file data; tar is what combines multiple files into one archive.
gunzip -k FILE.gzDecompresses a gzip file and keeps the compressed input. The resulting filename normally drops the .gz suffix.
sha256sum FILECalculates a SHA-256 digest of file contents, useful for detecting changes or comparing a download with a trusted published checksum. The hash alone does not identify who created the file.
sha256sum -c CHECKSUMS.sha256Checks files against a checksum list containing hashes and filenames, reporting OK or a mismatch. Relative filenames in the list are resolved from your current directory.
zip -r ARCHIVE.zip DIRECTORYCreate or update a ZIP archive from a directory tree. ZIP is useful for exchanging files with systems that do not normally use tar.
unzip ARCHIVE.zip -d DIRECTORYExtract a ZIP archive into a chosen directory. Existing file conflicts prompt by default; inspect names first with unzip -l.

System information and shutdown

CommandExplanation
uname -aShow the kernel version, machine architecture, and hostname.
hostnamectlShow the hostname, operating system, and virtualization details on a systemd host.
lscpuShow CPU architecture, logical processors, cores, and sockets.
free -hShow RAM and swap usage in readable units. The available column estimates memory usable by new applications.
uptimeShow running time and load averages for the last 1, 5, and 15 minutes. Load includes runnable tasks and tasks in uninterruptible sleep.
timedatectlShow system time, time zone, and clock synchronization status on systemd.
sudo rebootRestart the machine immediately through the system manager. Running services stop and remote sessions disconnect.
sudo shutdown -h +10Schedule shutdown in ten minutes and notify logged-in users. Save work before the machine powers off.
sudo shutdown -cCancel a pending shutdown before it starts.
date -u +'%Y-%m-%dT%H:%M:%SZ'Print the current UTC timestamp in a consistent format, useful when comparing logs from different time zones.
cat /etc/os-releaseIdentify the Linux distribution and release before choosing distribution-specific package or configuration commands.
sysctl net.ipv4.ip_forwardRead the kernel's IPv4 forwarding setting. Reading does not change it; persistent tuning belongs in the system's sysctl configuration.

Processes, signals, and performance

CommandExplanation
ps auxList processes with their owners, CPU and memory usage, state, and command line.
ps -eo pid,ppid,user,%cpu,%mem,stat,cmd --sort=-%cpuList processes sorted by CPU usage, including each parent process ID. The CPU percentage is averaged over the process lifetime.
pgrep -af 'PATTERN'Find processes whose full command line matches a regular expression, and print their IDs and commands.
topMonitor processes, CPU usage, and memory interactively. Press q to quit.
kill -TERM PIDAsk a process you own to terminate cleanly. Use its numeric process ID; another user's process generally requires sudo.
kill -KILL PIDForce a process you own to terminate without cleanup. Use this only when graceful termination fails; unsaved work can be lost.
kill -STOP PIDPause a process you own without ending it. Its resources stay allocated and clients may time out.
kill -CONT PIDResume a stopped process you own.
nice -n 10 COMMANDStart a command with a higher niceness value, giving it lower CPU scheduling priority under contention.
renice 10 -p PIDSet an existing process's niceness to 10. Without elevated privileges, you can generally only lower the scheduling priority of your own processes.
vmstat 1 5Sample memory, swap activity, CPU, and runnable tasks five times. The first CPU and I/O report summarizes time since boot; later reports cover one second.
iostat -xz 1 5Show extended disk I/O statistics at one-second intervals, omitting idle devices. Requires the sysstat package; the first report covers time since boot.
sudo lsof -p PIDList the files, sockets, and other open handles of a process. Requires lsof; elevated access lets you inspect other users' processes.
htopExplore processes in an interactive viewer with scrolling and filtering; press F10 or q to exit. Requires the htop package.
watch -n 2 'df -h'Rerun a disk-space check every two seconds and refresh its display. Ctrl+C stops watching without changing the filesystems.
time COMMANDMeasure a command's elapsed time and CPU time spent in user and kernel code. Bash's time keyword can also measure a pipeline.
timeout --kill-after=5s 30s COMMANDAsk a command to terminate after 30 seconds, then force termination five seconds later if necessary. GNU timeout normally returns 124 when its time limit is reached.
ulimit -nRead the current shell's soft limit on open file descriptors, inherited by newly started processes. A systemd service can have a different limit.
sudo strace -f -p PIDTrace a running process's system calls and newly created child processes to investigate blocked I/O or missing files. Requires strace; tracing adds overhead and may expose sensitive data.

Services with systemd

CommandExplanation
systemctl status SERVICE.serviceShow a service's current state and recent log entries.
systemctl --failedList systemd units currently marked as failed.
systemctl list-unit-files --type=serviceList installed service unit files and their enablement state.
systemctl cat SERVICE.serviceRead a service's unit file and configuration overrides from disk.
sudo systemctl start SERVICE.serviceStart a service now without changing its boot configuration.
sudo systemctl stop SERVICE.serviceStop a service now, interrupting its work and connected clients.
sudo systemctl restart SERVICE.serviceStop and start a service, briefly interrupting availability.
sudo systemctl reload SERVICE.serviceAsk a running service to reload its own configuration; reload support is required.
sudo systemctl enable --now SERVICE.serviceConfigure a service's automatic activation and start it now.
sudo systemctl disable --now SERVICE.serviceRemove automatic activation links and stop the service; dependencies can still start it.
sudo systemctl daemon-reloadReload systemd unit definitions after editing unit files; services keep running.

Logs and scheduled tasks

CommandExplanation
sudo journalctl -u SERVICE.service -n 100 --no-pagerPrint the latest 100 journal entries for a service. Elevated access includes system logs that may be hidden from your user.
sudo journalctl -f -u SERVICE.serviceFollow a service's new journal entries as they arrive. Press Ctrl+C to stop following.
sudo journalctl -b -1Read the previous boot's logs if the journal retained them across reboots.
sudo journalctl --since '1 hour ago' -p warningShow warnings and more severe journal entries from the last hour.
sudo dmesg --humanRead the kernel message buffer in a readable format, useful for hardware and driver errors.
systemctl list-timers --allList loaded systemd timers, including inactive ones, with their next and last runs.
crontab -lShow your user's recurring cron jobs. Requires cron or a compatible scheduler.
crontab -eEdit your user's recurring cron jobs. Each job uses minute, hour, day of month, month, day of week, then a command; use absolute paths because cron has a minimal environment.
sudo systemd-run --on-active=10m /ABSOLUTE/PATH/TO/COMMANDSchedule a command to run once as root in about ten minutes using a transient systemd timer. The timer does not survive a reboot.

Packages: APT on Debian and Ubuntu

CommandExplanation
sudo apt updateRefresh package metadata from configured repositories. Installed packages are unchanged.
apt list --upgradableList installed packages with newer versions in the downloaded metadata.
sudo apt upgradeInstall available package upgrades without removing installed packages. Review the proposed changes; updated services may restart.
apt search TERMSearch package names and descriptions in the local repository metadata.
apt show PACKAGEShow a package's description, version, dependencies, and other metadata.
sudo apt install PACKAGEInstall a package and its dependencies, or upgrade it if already installed. Package setup may start services.
sudo apt remove PACKAGERemove a package while usually retaining its system configuration files. Review dependent packages proposed for removal.
sudo apt purge PACKAGERemove a package and its managed system configuration. Files in users' home directories remain.
sudo apt autoremoveRemove automatically installed packages that are no longer needed as dependencies. Review the list before confirming.

Packages: DNF on Fedora and RHEL family

CommandExplanation
dnf check-updateCheck available package updates with DNF 4. Exit status 100 indicates available updates; no packages are upgraded.
dnf5 check-upgradeCheck available package updates with DNF 5. Exit status 100 indicates available updates; no packages are upgraded.
dnf search TERMSearch package names and summaries in enabled repositories.
dnf info PACKAGEShow package versions, descriptions, and repository information.
sudo dnf install PACKAGEInstall a package and its dependencies from enabled repositories. Review the transaction before accepting it.
sudo dnf upgradeUpgrade installed packages and resolve their dependencies. Updated services may need restarting, and a new kernel takes effect after reboot.
sudo dnf remove PACKAGERemove a package and packages that depend on it. Review the removal list because related software may also be removed.
rpm -qf /PATH/TO/FILEFind the installed RPM package that owns a file.

Disks, filesystems, and mounts

CommandExplanation
df -hShow used and available space on mounted filesystems in readable units.
df -iShow inode usage. A filesystem can run out of inodes even when byte capacity remains.
lsblk -fShow block devices with filesystem types, labels, UUIDs, and mount points.
sudo blkidProbe block devices for filesystem identifiers, useful when configuring persistent mounts by UUID.
findmnt --target /PATHIdentify the mounted filesystem containing a path and show its source and mount options.
sudo fdisk -lList disks and partition tables without changing them.
sudo mount /dev/DEVICE /MOUNTPOINTMount an existing filesystem at an existing directory until unmount or reboot. Files already in that directory are hidden while the mount is active.
sudo umount /MOUNTPOINTUnmount a filesystem before disconnecting or checking it. Close files and leave directories on that mount first.
sudo mkfs.ext4 /dev/DEVICECreate an ext4 filesystem on the chosen unmounted device, destroying its previous filesystem data. Confirm the device with lsblk first.
sudo e2fsck -f /dev/DEVICECheck an ext2, ext3, or ext4 filesystem and ask before repairs. The filesystem must be unmounted; repairs modify it.
sudo resize2fs /dev/DEVICEGrow an ext filesystem to fill its already enlarged partition or logical volume. Online growth requires filesystem and kernel support.
sudo xfs_growfs /MOUNTPOINTGrow a mounted XFS filesystem after enlarging its underlying partition or logical volume. This command does not shrink XFS.
du -sh DIRECTORYEstimate total disk space used by a directory tree, including hidden entries. -s prints only the total and -h uses readable units.
du -xhd 1 DIRECTORY | sort -hCompare directory sizes one level below a path and sort by size. GNU du -x stays on the same filesystem, avoiding traversal into other mounted filesystems.
sudo lsof +L1Find open files whose directory entries were deleted. Their disk space can remain occupied until the owning process closes the last handle.
findmnt --verify --verboseCheck /etc/fstab for parsing and usability problems without mounting its entries. Useful before relying on edited mount configuration at reboot.

Logical volumes and swap

CommandExplanation
sudo pvsList LVM physical volumes and their volume-group membership. Requires the LVM tools.
sudo vgsShow LVM volume groups, total capacity, and free space for logical volumes.
sudo lvs -o +devicesList logical volumes and the physical devices backing them.
sudo pvcreate /dev/DEVICEInitialize an unused device as an LVM physical volume. This writes metadata and can destroy existing data; verify the target first.
sudo vgcreate VG_NAME /dev/DEVICECreate a volume group from a prepared LVM physical volume that does not belong to another group.
sudo lvcreate -L 10G -n LV_NAME VG_NAMEAllocate a 10 GiB logical volume from free space in a volume group. Create a filesystem before mounting the new volume.
sudo lvextend -L +10G -r /dev/VG_NAME/LV_NAMEAdd 10 GiB to a logical volume and resize its supported filesystem. The volume group needs free space; check both sizes afterward because filesystem resizing can fail separately.
swapon --showList active swap devices and files with their sizes, usage, and priorities.
sudo mkswap /dev/DEVICEFormat an unused partition or logical volume as swap, destroying its previous contents. This prepares the area but does not activate it.
sudo swapon /dev/DEVICEActivate a prepared swap device for this boot. Persistent activation needs a matching /etc/fstab entry.
sudo swapoff /dev/DEVICEDisable a swap device and move its used pages elsewhere. Sufficient RAM or other swap space is required; heavy memory pressure can make this fail.

Networking, routes, DNS, and ports

CommandExplanation
ip -br addressShow network interfaces and assigned IPv4 and IPv6 addresses in a compact table.
ip -s linkShow interface state and packet counters, including errors and dropped packets.
ip routeShow the main IPv4 routing table, including the default gateway.
ip route get IP_ADDRESSAsk the kernel which route, interface, and source address it would use for a destination.
ip neighShow neighboring hosts and cached link-layer addresses, including IPv4 ARP and IPv6 neighbor discovery entries.
sudo ip link set dev INTERFACE upAdministratively enable a network interface. This does not assign an IP address and is not persistent network configuration.
sudo ip address add IP_ADDRESS/PREFIX dev INTERFACEAdd an address and network prefix length to an interface at runtime. Choose an unused address; a network manager may later replace this setting.
sudo ip address del IP_ADDRESS/PREFIX dev INTERFACERemove an interface address at runtime. Connections using that address can disconnect immediately.
sudo ip route add NETWORK/PREFIX via GATEWAY dev INTERFACEAdd a runtime route through a gateway reachable on the interface. The route affects traffic to that destination and is not saved across reboot.
sudo ip route del NETWORK/PREFIX via GATEWAY dev INTERFACERemove the matching runtime route. Traffic that relied on it may stop reaching its destination.
ping -c 4 HOSTSend four ICMP echo probes to test reachability and latency. Missing replies can also mean ICMP is filtered.
tracepath HOSTTrace network hops and discover path MTU without root. Requires tracepath; routers may omit responses.
sudo ss -lntupShow listening TCP and UDP sockets with numeric addresses and owning processes. Elevated access reveals processes belonging to other users.
ss -tn state establishedList established TCP connections with numeric addresses and ports.
getent ahosts HOSTResolve a hostname through the system's configured name-service sources, including hosts files and DNS.
resolvectl statusShow DNS servers and per-interface resolver settings when systemd-resolved is in use.
dig HOST A +shortQuery DNS for a host's IPv4 records and print a short answer. Requires dig, usually provided by dnsutils or bind-utils.
dig @DNS_SERVER HOST AAAAQuery a specific DNS server for IPv6 records, showing the response status and answer details.
nc -vz -w 3 HOST PORTWith OpenBSD-style netcat, attempt a TCP connection to one port with a three-second timeout. Success confirms TCP connectivity, not application or TLS health.
sudo tcpdump -ni INTERFACE -c 50 'tcp port 443'Capture up to 50 matching packets on an interface without resolving names. Requires tcpdump; packet capture can expose sensitive traffic and does not decrypt TLS.
ip -6 routeShow IPv6 routes, including the IPv6 default gateway. IPv4 and IPv6 maintain separate routing tables.

HTTP and TLS diagnostics

CommandExplanation
curl -I https://HOSTSend an HTTP HEAD request and show response headers. Some servers handle HEAD differently from GET.
curl --fail --location --output FILE https://HOST/PATHDownload a URL, following redirects and failing on HTTP errors. The output file is created or overwritten.
curl -v https://HOSTShow connection, TLS, request, and response details while fetching a URL. Verbose output can contain cookies or authorization data.
openssl s_client -connect HOST:443 -servername HOST -verify_hostname HOST -verify_return_error </dev/nullInspect a TLS handshake using SNI and check the certificate chain and hostname against the local trust store. Requires OpenSSL; certificate errors stop verification.

Host firewalls

CommandExplanation
sudo ufw status numberedShow UFW's status and numbered rules on a host managed by UFW.
sudo ufw allow PORT/tcpAdd a persistent UFW rule allowing inbound TCP traffic to a port. It takes effect immediately if UFW is enabled.
sudo ufw enableEnable UFW now and at boot. Add an allow rule for your actual SSH port before using this remotely; activation can interrupt connections.
sudo ufw delete RULE_NUMBERRemove a rule using its current number from ufw status numbered. Numbers change after removal, and deleting an allow rule can block access.
sudo firewall-cmd --get-active-zonesOn a firewalld host, show which zones are assigned to interfaces or source addresses.
sudo firewall-cmd --zone=ZONE --list-allShow the runtime services, ports, and other settings of a firewalld zone.
sudo firewall-cmd --permanent --zone=ZONE --add-port=PORT/tcpAllow an inbound TCP port in a zone's saved firewalld configuration. The change takes effect after reload or restart.
sudo firewall-cmd --reloadReplace firewalld's runtime settings with its saved configuration. Runtime-only changes are normally lost, so confirm saved SSH access first.
sudo nft list rulesetInspect the active nftables ruleset, including rules created by a firewall manager using nftables.

SSH, SCP, and rsync

CommandExplanation
ssh USER@HOSTOpen an encrypted remote shell. On first connection, verify the server's host-key fingerprint through a trusted channel.
ssh -p PORT -i /PATH/TO/PRIVATE_KEY USER@HOSTConnect to a non-default SSH port using a specific private key. The server must authorize the corresponding public key.
ssh -v USER@HOSTPrint SSH connection and authentication diagnostics to investigate login failures.
ssh-keygen -t ed25519 -f ~/.ssh/KEY_NAMEGenerate an Ed25519 key pair at the chosen unused path; choose a passphrase when prompted. Keep the private key local and share only the .pub file.
ssh-copy-id -i ~/.ssh/KEY_NAME.pub USER@HOSTInstall a public key in the remote user's authorized_keys. Requires ssh-copy-id and an existing way to log in to that account.
ssh -N -L 127.0.0.1:LOCAL_PORT:DEST_HOST:DEST_PORT USER@SSH_HOSTForward a localhost TCP port through SSH to a destination reachable from the SSH server. The tunnel lasts while the SSH connection stays open.
scp FILE USER@HOST:/REMOTE/DIRECTORY/Copy a local file to an existing remote directory over SSH. An existing file with the same name is overwritten.
scp -P PORT USER@HOST:/REMOTE/FILE ./Copy a remote file to the current directory using a custom SSH port. SCP uses uppercase -P for the port and can overwrite a local file of the same name.
rsync -av --dry-run SOURCE/ USER@HOST:/DESTINATION/Preview a transfer over SSH without changing files; rsync must be installed on both ends. The trailing slash copies SOURCE contents, and the default update check uses file size and modification time.
rsync -av SOURCE/ USER@HOST:/DESTINATION/Transfer directory contents over SSH in archive mode, selecting updates by size and modification time rather than comparing all file contents. Matching destination files can be replaced; destination-only files remain.
ssh -J USER@BASTION USER@TARGETReach a target through an SSH jump host while keeping the final SSH session end-to-end between your client and the target.
ssh-add /PATH/TO/PRIVATE_KEYLoad a private key into the running SSH agent, prompting for its passphrase when needed. The agent can then authenticate without repeatedly asking for the key's passphrase.

Git: version control

CommandExplanation
git clone URLDownload a repository and its history into a new local directory.
git status --shortSee changed, staged, and untracked files before committing. The left status column describes the staging area; the right describes the working tree.
git diffShow tracked changes that have not been staged. New, untracked files are not included.
git diff --stagedReview exactly the changes currently staged for the next commit.
git add FILEStage the current contents of a file for the next commit. Further edits need to be staged again.
git commit -m 'Describe the change'Save the staged changes as a local commit with a useful message. This does not upload them.
git log --oneline --graph --all -20Show the latest 20 commits reachable from all refs, including branch tips, as a compact graph.
git show COMMITInspect a commit's message and patch; replace COMMIT with its hash or a reference such as HEAD.
git switch -c BRANCHCreate a new branch from the current commit and switch to it.
git switch BRANCHSwitch to an existing branch. Git refuses if switching would overwrite conflicting local changes.
git fetch originDownload new remote commits and update remote-tracking references without merging into your branch.
git pull --ff-onlyFetch and update the current branch only when no merge commit is needed. It stops if local and remote histories have diverged.
git merge BRANCHIntegrate another branch into the current one. Conflicting edits must be resolved before completing the merge.
git push -u origin BRANCHUpload the branch and set origin/BRANCH as its upstream for later pulls and pushes.
git restore --staged FILERemove a file's changes from the staging area while keeping them in the working tree.
git restore FILEDiscard unstaged edits in a tracked file by restoring its staged version. Those discarded edits are not automatically recoverable.
git revert COMMITCreate a new commit that reverses an earlier commit's changes, preserving shared history.
git stash push -u -m 'Work in progress'Temporarily save tracked changes and untracked files, leaving ignored files alone. Useful before switching tasks.
git stash popReapply the most recent stash and remove it if application succeeds; conflicts leave the stash available.
git remote -vShow remote names and their fetch/push URLs to check which repository you are using.
git reflogShow recent local movements of HEAD, useful for finding commits after a mistaken reset or branch change.

Docker: images and containers

CommandExplanation
docker versionShow Docker client and server versions. A missing server response often means the daemon is unavailable or inaccessible.
docker context lsList Docker connection contexts and identify the active daemon; commands can target a remote machine.
docker pull IMAGE:TAGDownload an image from a registry. A tag can move; use an image digest when you need an immutable reference.
docker build -t IMAGE:TAG .Build an image using the Dockerfile and build context in the current directory. Use .dockerignore to exclude secrets and unnecessary files.
docker image lsList images stored in the selected Docker daemon, including tags and sizes.
docker run --rm -it --entrypoint sh IMAGE:TAGStart an interactive shell instead of the image's usual entrypoint, and remove the new container when it exits. The image must contain sh.
docker run -d --name web -p 127.0.0.1:8080:80 IMAGE:TAGRun a container in the background and publish its port 80 on host port 8080, accessible only through the host's loopback interface.
docker ps -aList running and stopped containers. Without -a, only running containers are shown.
docker logs --tail 100 -f CONTAINERShow the last 100 log lines and follow new output from the container's logging driver. Press Ctrl+C to stop following.
docker exec -it CONTAINER shOpen another shell inside an already running container. This does not start a new container, and the image must contain sh.
docker inspect CONTAINERShow detailed container configuration, mounts, networks, and state as JSON. The output can include environment secrets.
docker statsWatch CPU, memory, network, and disk I/O usage for running containers.
docker stop CONTAINERRequest a graceful stop, then force termination if the container does not exit within the stop timeout.
docker start CONTAINERStart an existing stopped container with its previous configuration and writable layer.
docker rm CONTAINERRemove a stopped container and its writable layer. Named volumes remain until explicitly removed.
docker volume create DATACreate a named volume whose data can outlive the containers that mount it.
docker run -d --mount type=volume,src=DATA,dst=/data IMAGE:TAGMount a named volume at /data in a new container. Data written there is stored outside the container's writable layer.
docker network create NETWORKCreate a user-defined bridge network for local containers, including name-based discovery between attached containers.
docker network inspect NETWORKInspect a Docker network and the containers connected to it.
docker login REGISTRYAuthenticate to a registry using the supported interactive flow. Prefer a configured credential helper to plaintext credential storage.
docker tag IMAGE:TAG REGISTRY/REPOSITORY:TAGAdd another reference to an existing local image so it can be pushed to the intended registry and repository.
docker push REGISTRY/REPOSITORY:TAGUpload an image to a registry; requires permission to write to that repository.
docker system dfShow disk space used by images, containers, volumes, and the build cache before deciding what to remove.
docker image pruneRemove dangling images after confirmation. It does not remove every unused tagged image unless -a is added.

Docker Compose: multiple services

CommandExplanation
docker compose config --quietValidate the Compose configuration without printing its resolved contents. Run in the project directory or supply -f FILE.
docker compose up -d --buildBuild images as needed, create or recreate services, and run them in the background.
docker compose psList the project's containers, status, and published ports.
docker compose logs -f SERVICEFollow logs for one Compose service; omit SERVICE to follow all services in the project.
docker compose exec SERVICE shOpen a shell in a running service container, provided its image contains sh.
docker compose pullFetch service images from registries. Running containers keep their old images until recreated.
docker compose downStop and remove the project's containers and ordinary project networks. Named volumes are kept; adding --volumes would delete project-managed volumes.

Kubernetes: context and discovery

CommandExplanation
kubectl versionShow client and API server versions. Reaching the server requires a working kubeconfig and network access.
kubectl config get-contextsList configured clusters, users, and default namespaces. The asterisk marks the context kubectl uses by default.
kubectl config current-contextCheck the active context before changing cluster resources. A context selects the cluster and credentials, not just a namespace.
kubectl config use-context CONTEXTChange the active context for subsequent kubectl commands.
kubectl config set-context --current --namespace=NAMESPACESet the default namespace in the current context. An explicit -n on a command overrides it.
kubectl --context=CONTEXT -n NAMESPACE get podsTarget a specific context and namespace for one command without changing the defaults.
kubectl cluster-infoShow the API server address and discovered cluster service endpoints. This is a quick connectivity check, not a full health assessment.
kubectl api-resourcesList resource kinds supported by this cluster, their short names, API groups, and whether they belong to a namespace.
kubectl explain deployment.spec.template.spec.containersLook up the schema for a Deployment's container definitions before writing YAML.
kubectl get namespacesList namespaces, which organize namespaced resources within the same cluster.
kubectl create namespace NAMESPACECreate a namespace. It does not automatically provide network isolation or permissions for users.
kubectl get nodes -o wideList nodes with readiness, roles, versions, and addresses. Nodes are cluster-scoped, so -n does not apply.
kubectl get pods -AList pods across all namespaces, including system workloads. This requires cluster-wide list permission; namespace-only access does not return a partial list.
kubectl get pods -n NAMESPACE -o wideShow pods in one namespace with their IP addresses and assigned nodes.
kubectl get pods -n NAMESPACE -l app=APPFilter pods by a label. This matches the app label's value, not the pod name.
kubectl get pods -n NAMESPACE --watchPrint pod changes as they happen; Ctrl+C ends the watch without affecting the pods.

Kubernetes: manifests and workloads

CommandExplanation
kubectl apply --dry-run=server -f FILEAsk the API server to validate a manifest and run dry-run admission checks without saving the resource. Requires server access.
kubectl diff -f FILECompare a manifest's intended state with the live resources before applying it. Exit code 1 means differences were found.
kubectl apply -f FILECreate or update resources from a YAML or JSON manifest. Removing an object from the file alone does not delete it from the cluster.
kubectl apply -k DIRECTORYBuild and apply a directory's Kustomize configuration, including its patches and overlays.
kubectl kustomize DIRECTORYRender a Kustomize directory as YAML without applying it, so you can inspect the combined manifests.
kubectl get deployment APP -n NAMESPACE -o yamlInspect the live Deployment, including configuration, metadata, and status. Live output contains server-managed fields and is not a clean source manifest.
kubectl create deployment APP --image=IMAGE:TAG -n NAMESPACE --dry-run=client -o yamlGenerate a starter Deployment manifest locally; it is printed, not created in the cluster.
kubectl rollout status deployment/APP -n NAMESPACE --timeout=120sWait up to two minutes for a Deployment rollout to finish, useful after applying a change.
kubectl set image deployment/APP CONTAINER=IMAGE:TAG -n NAMESPACEUpdate one container's image in a Deployment, starting a rollout. Update the source manifest too so a later apply does not undo it.
kubectl scale deployment/APP --replicas=3 -n NAMESPACESet a Deployment's desired replica count to three. An HPA can later change the count if one manages this workload.
kubectl rollout restart deployment/APP -n NAMESPACETrigger replacement pods using the Deployment's rollout strategy, for example to reload configuration read only at startup.
kubectl rollout history deployment/APP -n NAMESPACEList retained Deployment revisions to investigate an update or choose a rollback target.
kubectl rollout undo deployment/APP -n NAMESPACERestore the previous retained pod-template revision. This does not undo external database changes or every Deployment setting.
kubectl get deployments,statefulsets,daemonsets -n NAMESPACECompare desired and ready replicas across the main workload controllers. A DaemonSet normally runs a pod on each eligible node.
kubectl get jobs,cronjobs -n NAMESPACEInspect one-off jobs and scheduled jobs, including completion counts and scheduling status.
kubectl create job JOB --from=cronjob/CRONJOB -n NAMESPACEStart a one-off Job using an existing CronJob's template without waiting for its next scheduled run.
kubectl patch cronjob CRONJOB -n NAMESPACE --type=merge -p '{"spec":{"suspend":true}}'Suspend future CronJob runs; jobs already started continue. Set suspend to false to resume scheduling.
kubectl delete -f FILEDelete the resources identified by a manifest. This can remove running workloads; deleting a PVC may also delete its backing volume under the reclaim policy.
kubectl edit deployment APP -n NAMESPACEOpen the live Deployment in an editor and submit changes when you save. Record the same change in its source manifest to avoid configuration drift.
kubectl wait --for=condition=Ready pod/POD -n NAMESPACE --timeout=60sWait up to one minute for a pod to report Ready. This checks a condition, unlike a fixed sleep that cannot tell whether startup succeeded.
kubectl run POD --image=IMAGE:TAG --restart=Never -n NAMESPACECreate a standalone pod for a small experiment using the image's default command. No Deployment controller will replace this pod if it is deleted.
kubectl label pod POD app=APP --overwrite -n NAMESPACESet or replace a pod label. Labels can change which Services or policies select the pod; controller-managed pods should get lasting labels through their template.
kubectl annotate deployment APP owner=TEAM --overwrite -n NAMESPACEAttach descriptive metadata to a Deployment without changing its pod template. Annotations store information for people and tools; they are not label selectors.

Kubernetes: configuration, networking, and storage

CommandExplanation
kubectl create configmap CONFIG --from-file=FILE -n NAMESPACECreate a ConfigMap from a file; the filename becomes the data key. ConfigMaps are for non-secret configuration.
kubectl create secret generic SECRET --from-file=FILE -n NAMESPACECreate a Secret from a local file without placing its contents in the command line. Base64 representation does not itself encrypt the stored data.
kubectl get configmaps,secrets -n NAMESPACEList configuration objects and Secret metadata without printing their data values.
kubectl get services -n NAMESPACEShow Service types, cluster addresses, external addresses, and ports. Most Services select their backend pods using labels.
kubectl expose deployment APP --port=80 --target-port=8080 -n NAMESPACECreate a ClusterIP Service forwarding service port 80 to selected pods on port 8080. This alone does not expose the app to the internet.
kubectl get endpointslices -n NAMESPACE -l kubernetes.io/service-name=SERVICE -o yamlInspect a Service's backend addresses and readiness conditions in YAML to investigate routing problems.
kubectl port-forward service/SERVICE 8080:80 -n NAMESPACEForward local port 8080 to the Service's port 80 through one selected pod. The tunnel lasts while the command runs and binds to localhost by default.
kubectl get ingress -n NAMESPACEInspect HTTP routing rules and assigned addresses. An installed Ingress controller must implement those rules.
kubectl get gateways,httproutes -n NAMESPACEInspect Gateway API entry points and routes. Requires Gateway API resources and a compatible controller to be installed.
kubectl get networkpolicies -n NAMESPACEList network restrictions defined for pods. Enforcement depends on the cluster's networking plugin supporting NetworkPolicy.
kubectl get pvc -n NAMESPACEList PersistentVolumeClaims and their binding state; Pending often indicates a provisioning or matching problem.
kubectl get pv,storageclassesInspect cluster-wide volumes and storage provisioning classes, including reclaim policies and provisioners.
kubectl describe pvc CLAIM -n NAMESPACERead a claim's storage requirements, binding information, and events to investigate a failed volume allocation.
kubectl describe resourcequotas,limitranges -n NAMESPACEInspect namespace-wide resource budgets and default or allowed container resource values.
kubectl get hpa -n NAMESPACEInspect HorizontalPodAutoscalers and their current versus target metrics. Metrics collection must be available for scaling to work.

Kubernetes: troubleshooting

CommandExplanation
kubectl describe pod POD -n NAMESPACERead scheduling decisions, container state, probes, mounts, and recent events. Start here for Pending, crash, or readiness problems.
kubectl logs POD -c CONTAINER -n NAMESPACE --tail=100Read the last 100 log lines of one container. Specify the container when a pod has more than one.
kubectl logs POD -c CONTAINER -n NAMESPACE --previousRead logs from the previous instance of a restarted container, if retained. Useful for CrashLoopBackOff investigations.
kubectl logs -l app=APP --all-containers=true --prefix=true -n NAMESPACE --since=10m --tail=-1Collect all retained log lines from the last ten minutes across matching pods and containers, with source prefixes. --tail=-1 removes the label-selector default of ten lines per container.
kubectl exec -it POD -c CONTAINER -n NAMESPACE -- shRun an interactive shell in a running container; the image must contain sh. Everything after -- is the container command.
kubectl cp NAMESPACE/POD:/tmp/FILE ./FILE -c CONTAINERCopy a file from a container to the local machine. kubectl cp requires tar inside the container.
kubectl get events -n NAMESPACE --sort-by=.metadata.creationTimestampList events in creation order to spot failed scheduling, image pulls, and volume mounts. Events have limited retention.
kubectl top pods -n NAMESPACE --containersShow recent CPU and memory usage per container. Requires the resource metrics API, usually supplied by Metrics Server.
kubectl top nodesCompare recent CPU and memory usage across nodes; this uses the resource metrics API, not historical monitoring data.
kubectl debug POD -it --image=DEBUG_IMAGE --target=CONTAINER --profile=general -n NAMESPACEAdd an ephemeral debugging container to a pod when the app image lacks tools. Target process visibility depends on runtime support and permissions.
kubectl get pod POD -n NAMESPACE -o jsonpath='{.status.containerStatuses[*].restartCount}'Extract container restart counters without printing the full pod JSON. jsonpath selects fields from API output.
kubectl get pods -A --field-selector=spec.nodeName=NODEFind all pods scheduled on a particular node, useful before maintenance or when investigating node failures.

Kubernetes: access and security

CommandExplanation
kubectl auth can-i create deployments -n NAMESPACEAsk whether your current identity is authorized to create Deployments in the namespace.
kubectl auth can-i --list -n NAMESPACEList allowed actions in a namespace for the current identity; authorization plugins can limit how complete this list is.
kubectl get roles,rolebindings -n NAMESPACEInspect namespace-level RBAC roles and the bindings assigning those permissions to identities.
kubectl get clusterroles,clusterrolebindingsInspect cluster-wide role definitions and bindings. A ClusterRoleBinding grants permissions across the cluster.
kubectl create serviceaccount SERVICEACCOUNT -n NAMESPACECreate an identity for workloads. It has no extra permissions until suitable roles are bound to it.
kubectl create role pod-reader --verb=get,list,watch --resource=pods -n NAMESPACEDefine a namespace role that can read pod objects but cannot modify them or automatically read their logs.
kubectl create rolebinding pod-readers --role=pod-reader --serviceaccount=NAMESPACE:SERVICEACCOUNT -n NAMESPACEGrant the pod-reader role to a ServiceAccount within this namespace. Replace both namespace placeholders consistently.
kubectl label namespace NAMESPACE pod-security.kubernetes.io/enforce=restricted --overwriteEnforce the Restricted Pod Security Standard for new pod admissions in this namespace. Incompatible workloads can be rejected; existing pods are not retroactively evicted.

Helm: application packages

CommandExplanation
helm repo add REPO HTTPS_URLRegister a Helm chart repository under a local name. This does not install anything into a cluster.
helm repo updateRefresh indexes of configured chart repositories so searches see current chart versions.
helm search repo REPO/CHART --versionsList chart versions in local repository indexes. The chart version and application version can differ.
helm show values REPO/CHARTInspect a chart's default configuration before writing your own values file.
helm lint CHART_DIRECTORYCheck a local chart for common structural and template problems. This is not proof that it will run successfully in a cluster.
helm template RELEASE REPO/CHART -f VALUES_FILERender chart templates locally without installing them; rendered output can contain Secret data.
helm upgrade --install RELEASE REPO/CHART --version VERSION -n NAMESPACE --create-namespace -f VALUES_FILE --wait --timeout 5mInstall or update a release from a pinned chart version and wait up to five minutes for readiness. A timeout does not itself undo all changes.
helm list -AList Helm releases across all namespaces. This requires cluster-wide access to the configured release storage, normally Secrets.
helm status RELEASE -n NAMESPACEInspect a release's state, revision, and chart notes after installation or an upgrade.
helm history RELEASE -n NAMESPACEList release revisions so you can identify a previous deployment to roll back to.
helm rollback RELEASE REVISION -n NAMESPACE --waitRestore a retained release revision. This does not reverse application-level data migrations.
helm uninstall RELEASE -n NAMESPACERemove a Helm release and its managed resources. Persistent data and hook resources can have separate retention behavior.

Kubernetes: node and cluster administration

CommandExplanation
kubectl describe node NODEInspect readiness conditions, taints, capacity, allocated resource requests, and node events. Allocated requests are not actual live usage.
kubectl get --raw='/readyz?verbose'Ask the API server for readiness checks; authorization must allow this endpoint. A ready API server does not prove every workload is healthy.
kubectl get pods -n kube-system -o wideInspect system pods such as DNS and networking components. Managed services may hide control-plane components.
kubectl get pdb -AReview PodDisruptionBudgets and allowed disruptions before draining nodes. These budgets constrain voluntary evictions, not hardware failures.
kubectl cordon NODEMark a node unschedulable for ordinary new pods. Existing pods keep running.
kubectl drain NODE --ignore-daemonsets --timeout=10mCordon the node and evict eligible pods while respecting disruption budgets. DaemonSet pods stay; local emptyDir data or unmanaged pods can block the drain.
kubectl uncordon NODEAllow ordinary new pods to be scheduled on the node again after maintenance. It does not automatically rebalance existing pods.
kubectl label node NODE workload=backend --overwriteSet a node label that workloads can target through node selectors or affinity. The label alone does not move any pods.
kubectl taint nodes NODE dedicated=backend:NoSchedulePrevent new pods without a matching toleration from scheduling onto the node. Existing pods are not evicted by NoSchedule.
kubectl taint nodes NODE dedicated:NoSchedule-Remove the NoSchedule taint with key dedicated, permitting pods that were excluded by that taint.
kubectl get crdList CustomResourceDefinitions, which extend the cluster API with additional resource types used by operators and other tools.
sudo journalctl -u kubelet -n 100 --no-pagerOn a Linux node using systemd, inspect recent kubelet logs when pods cannot start or the node becomes NotReady.
sudo crictl ps -aOn a node with crictl configured for its CRI runtime, list containers including exited ones. This works even if the Kubernetes API is unreachable.
sudo crictl logs CONTAINER_IDRead a node-local container's logs through the CRI runtime, useful when kubectl logs cannot reach the node.
sudo crictl imagesList images available through the node's configured CRI runtime. With containerd or CRI-O, this inventory is separate from Docker's.

Self-managed clusters: kubeadm and etcd

CommandExplanation
sudo kubeadm init --config CLUSTER_CONFIGBootstrap a self-managed control plane from a prepared kubeadm configuration. Nodes need a compatible container runtime and prerequisites; a CNI networking plugin must also be installed.
sudo kubeadm token create --print-join-commandOn a kubeadm control-plane node, generate a bootstrap token and print the worker join command. Treat its token as a credential and share it only with the joining administrator.
sudo kubeadm join API_SERVER:6443 --token TOKEN --discovery-token-ca-cert-hash sha256:HASHJoin a prepared worker to a self-managed kubeadm cluster, using the control plane's token and CA hash. Managed services normally manage node joins themselves.
sudo kubeadm upgrade planCheck supported upgrades for a self-managed kubeadm cluster. Follow the version-specific procedure; Kubernetes minor versions must not be skipped.
sudo kubeadm upgrade apply VERSIONPerform the first control-plane upgrade step for a chosen supported version after prerequisites and backups. This is not the whole upgrade: remaining nodes, kubelets, kubectl, and add-ons need coordinated updates too.
sudo kubeadm upgrade nodeApply node-local kubeadm upgrade changes on additional control-plane or worker nodes. Follow the appropriate drain, package-update, and restart sequence for that node type.
sudo kubeadm certs check-expirationInspect expiry dates of certificates managed by kubeadm on a control-plane node. Externally managed certificates need their own renewal process.
sudo kubeadm certs renew allRenew this node's kubeadm-managed certificates using local CA keys; repeat on every control-plane node. CA certificates remain unchanged; restart affected components and refresh copied kubeconfigs afterward.
etcdctl --endpoints=HTTPS_ENDPOINT --cacert=CA_FILE --cert=CERT_FILE --key=KEY_FILE endpoint healthCheck an authorized etcd endpoint's health using trusted TLS credentials. This is for administrators with direct etcd access, usually in self-managed clusters.
etcdctl --endpoints=HTTPS_ENDPOINT --cacert=CA_FILE --cert=CERT_FILE --key=KEY_FILE snapshot save BACKUP.dbSave an etcd snapshot from one endpoint. It contains Kubernetes cluster state, including Secrets, but not the application data stored on persistent volumes.
etcdutl snapshot status BACKUP.db --write-out=tableInspect a snapshot's revision, hash, key count, and size offline with a compatible etcdutl version. This does not prove a complete disaster recovery will succeed.
etcdutl snapshot restore BACKUP.db --data-dir=NEW_DATA_DIRECTORYBuild a restored etcd data directory offline. Do not overwrite live data; a Kubernetes recovery also needs coordinated member configuration and the version-appropriate revision-bump/compaction procedure.