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.
433 command examples
No matching commands. Try another search term or select all topics.
Help and command discovery
| Command | Explanation |
|---|---|
man COMMAND | Opens the command's manual, including options and examples. Search with /TEXT, jump to the next match with n, and quit with q. |
man -k KEYWORD | Searches manual-page names and short descriptions for a keyword; useful when you know the task but not the command. |
help cd | Shows Bash's own help for the cd builtin. Builtins run inside the shell and may behave differently from similarly named external programs. |
COMMAND --help | Prints a quick usage summary for commands that support --help, including their accepted flags and arguments. |
type -a COMMAND | Shows how Bash resolves a command name, including aliases, functions, builtins and matching executables. -a lists all matches instead of only the first. |
command -v COMMAND | Reports 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. |
Files, directories and links
| Command | Explanation |
|---|---|
touch FILE | Creates an empty file if it does not exist; otherwise updates its access and modification timestamps without changing its contents. |
mkdir -p DIRECTORY/SUBDIRECTORY | Creates the directory and any missing parent directories. -p also accepts directories that already exist. |
cp -i SOURCE DESTINATION | Copies a file and asks before overwriting an existing destination. If DESTINATION is a directory, the copy keeps the source filename inside it. |
cp -a SOURCE_DIRECTORY DESTINATION | Copies a directory tree, preserving links and as much metadata as possible; existing files may be overwritten. An existing destination directory receives the source directory inside it, while a new destination becomes the copy's name. |
mv -i SOURCE DESTINATION | Moves or renames a file or directory, asking before replacing an existing destination. A move within one filesystem usually changes the path without copying file contents. |
rm -i FILE | Removes a file after confirmation; it does not move the file to a trash folder. If FILE is a symbolic link, the link itself is removed. |
rm -rI DIRECTORY | Recursively deletes a directory and its contents. GNU rm's uppercase -I asks once before this recursive deletion; lowercase -i asks about individual removals. |
rmdir DIRECTORY | Removes an empty directory and fails if it still contains files or subdirectories. Useful when you want to preserve any remaining contents. |
file FILE | Inspects a file's contents and metadata to identify its type, such as text, an executable or compressed data. The result does not rely only on the filename extension. |
stat FILE | Shows detailed file metadata, including size, permissions, owner, inode and timestamps. Modification time describes content changes; change time describes inode metadata changes, not creation. |
ln FILE HARD_LINK | Creates another filename for the same file data on the same filesystem. Both names share changes, and removing one name leaves the other usable. |
ln -s TARGET SYMBOLIC_LINK | Creates a symbolic link that stores a path to a file or directory and can cross filesystems. A relative target is resolved from the link's directory, and the link breaks if its target disappears. |
readlink SYMBOLIC_LINK | Prints the target path stored in a symbolic link. The printed path can be relative and does not prove that the target currently exists. |
realpath PATH | Prints a normalized absolute path, resolving symbolic links, the current-directory marker (.) and parent-directory markers (..). Useful for seeing where a path actually leads. |
Read file contents
| Command | Explanation |
|---|---|
cat FILE | Writes the whole file to standard output. With several filenames, cat prints their contents consecutively in the supplied order. |
less FILE | Opens a file in a scrollable viewer without editing it. Search with /TEXT, continue with n, and exit with q. |
head -n 20 FILE | Prints 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 FILE | Prints 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
| Command | Explanation |
|---|---|
nano FILE | Opens 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 FILE | Opens 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 SESSION | Starts 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 detach | Detaches 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 SESSION | Reconnects 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
| Command | Explanation |
|---|---|
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 -1 | Finds 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' FILE | Prints 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' DIRECTORY | Searches 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' FILE | Searches 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' FILE | Matches 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:]]*(#|$)' FILE | Prints 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' FILE | Shows 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' DIRECTORY | Search 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 -l | Pass 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
| Command | Explanation |
|---|---|
sort -n FILE | Sorts 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 -nr | Counts 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 FILE | Extracts 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}' FILE | Prints 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' FILE | Prints only lines 10 through 20. -n suppresses sed's normal output, and p explicitly prints the selected range. |
sed 's/OLD/NEW/g' FILE | Prints 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 FILE | Counts 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:]' < FILE | Converts 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_FILE | Compare two text files using unified diff format. Exit status 1 means differences exist; it does not mean the comparison failed. |
base64 FILE | Encode file bytes as printable Base64 text; this is encoding, not encryption. GNU base64 wraps output lines unless -w 0 is added. |
base64 --decode FILE | Decode 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
| Command | Explanation |
|---|---|
jq '.' FILE.json | Parses 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.json | Reads 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.json | Iterates 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.json | Passes 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.yaml | Reads 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.yaml | Updates 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
| Command | Explanation |
|---|---|
COMMAND > FILE | Redirects 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 >> FILE | Appends standard output to the end of a file instead of replacing its contents. Creates the file if it does not exist. |
COMMAND 2> ERRORS.log | Redirects standard error (stream 2) into a file, replacing any existing contents. Normal output still goes to the terminal. |
COMMAND > OUTPUT.log 2>&1 | Sends both standard output and standard error to one file. Order matters: 2>&1 copies standard output's destination after > has redirected it. |
COMMAND < FILE | Supplies 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 -l | Connects 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.log | Shows 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/null | Writes 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
| Command | Explanation |
|---|---|
id | Shows 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 USER | Looks 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 SCRIPT | Adds execute permission for the file's owner while preserving other permission bits. u means owner, g means group and o means others. |
chmod 640 FILE | Sets 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 DIRECTORY | Gives 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 FILE | Changes a file's owner and group. Without -R this affects only the named path, not the contents of a directory. |
chgrp GROUP FILE | Changes only the file's group. A file owner can normally choose one of their own groups; other changes require administrator privileges. |
umask 077 | Masks 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 COMMAND | Runs 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 COMMAND | Runs 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 USER | Creates 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 USER | Sets or changes an account's password through an interactive prompt. With no username and without sudo, passwd changes your own password. |
sudo groupadd GROUP | Creates a local group for sharing permissions among accounts. Creating a group does not automatically add users to it. |
sudo usermod -aG GROUP USER | Adds 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 FILE | Read 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 FILE | Grant 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
| Command | Explanation |
|---|---|
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: ' name | Prompts 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'; fi | Runs 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 DIRECTORY | Runs 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' >&2 | Prints 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"; done | Runs 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 < FILE | Reads 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 ARGUMENT | Runs 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.sh | Executes 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 1 | Ends 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 pipefail | Makes 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 PATH | Print the PATH environment variable: a colon-separated list of directories searched for external commands. |
env APP_ENV=test COMMAND | Run one command with an environment variable override without changing the calling shell's environment. |
unset APP_ENV | Remove 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 20 | Show 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.sh | Check a script's Bash syntax without running its commands. This does not detect every logic or runtime error. |
bash -x SCRIPT.sh | Run a script while printing commands after expansion for debugging. Expanded values can reveal secrets in the trace. |
shellcheck SCRIPT.sh | Statically 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
| Command | Explanation |
|---|---|
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 -l | Lists 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 %1 | Brings 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 %1 | Resumes 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
| Command | Explanation |
|---|---|
tar -czf ARCHIVE.tar.gz DIRECTORY | Creates 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.gz | Lists 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 DIRECTORY | Extracts 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 FILE | Compresses 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.gz | Decompresses a gzip file and keeps the compressed input. The resulting filename normally drops the .gz suffix. |
sha256sum FILE | Calculates 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.sha256 | Checks 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 DIRECTORY | Create 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 DIRECTORY | Extract a ZIP archive into a chosen directory. Existing file conflicts prompt by default; inspect names first with unzip -l. |
System information and shutdown
| Command | Explanation |
|---|---|
uname -a | Show the kernel version, machine architecture, and hostname. |
hostnamectl | Show the hostname, operating system, and virtualization details on a systemd host. |
lscpu | Show CPU architecture, logical processors, cores, and sockets. |
free -h | Show RAM and swap usage in readable units. The available column estimates memory usable by new applications. |
uptime | Show running time and load averages for the last 1, 5, and 15 minutes. Load includes runnable tasks and tasks in uninterruptible sleep. |
timedatectl | Show system time, time zone, and clock synchronization status on systemd. |
sudo reboot | Restart the machine immediately through the system manager. Running services stop and remote sessions disconnect. |
sudo shutdown -h +10 | Schedule shutdown in ten minutes and notify logged-in users. Save work before the machine powers off. |
sudo shutdown -c | Cancel 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-release | Identify the Linux distribution and release before choosing distribution-specific package or configuration commands. |
sysctl net.ipv4.ip_forward | Read the kernel's IPv4 forwarding setting. Reading does not change it; persistent tuning belongs in the system's sysctl configuration. |
Processes, signals, and performance
| Command | Explanation |
|---|---|
ps aux | List processes with their owners, CPU and memory usage, state, and command line. |
ps -eo pid,ppid,user,%cpu,%mem,stat,cmd --sort=-%cpu | List 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. |
top | Monitor processes, CPU usage, and memory interactively. Press q to quit. |
kill -TERM PID | Ask a process you own to terminate cleanly. Use its numeric process ID; another user's process generally requires sudo. |
kill -KILL PID | Force a process you own to terminate without cleanup. Use this only when graceful termination fails; unsaved work can be lost. |
kill -STOP PID | Pause a process you own without ending it. Its resources stay allocated and clients may time out. |
kill -CONT PID | Resume a stopped process you own. |
nice -n 10 COMMAND | Start a command with a higher niceness value, giving it lower CPU scheduling priority under contention. |
renice 10 -p PID | Set an existing process's niceness to 10. Without elevated privileges, you can generally only lower the scheduling priority of your own processes. |
vmstat 1 5 | Sample 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 5 | Show 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 PID | List the files, sockets, and other open handles of a process. Requires lsof; elevated access lets you inspect other users' processes. |
htop | Explore 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 COMMAND | Measure 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 COMMAND | Ask 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 -n | Read 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 PID | Trace 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
| Command | Explanation |
|---|---|
systemctl status SERVICE.service | Show a service's current state and recent log entries. |
systemctl --failed | List systemd units currently marked as failed. |
systemctl list-unit-files --type=service | List installed service unit files and their enablement state. |
systemctl cat SERVICE.service | Read a service's unit file and configuration overrides from disk. |
sudo systemctl start SERVICE.service | Start a service now without changing its boot configuration. |
sudo systemctl stop SERVICE.service | Stop a service now, interrupting its work and connected clients. |
sudo systemctl restart SERVICE.service | Stop and start a service, briefly interrupting availability. |
sudo systemctl reload SERVICE.service | Ask a running service to reload its own configuration; reload support is required. |
sudo systemctl enable --now SERVICE.service | Configure a service's automatic activation and start it now. |
sudo systemctl disable --now SERVICE.service | Remove automatic activation links and stop the service; dependencies can still start it. |
sudo systemctl daemon-reload | Reload systemd unit definitions after editing unit files; services keep running. |
Logs and scheduled tasks
| Command | Explanation |
|---|---|
sudo journalctl -u SERVICE.service -n 100 --no-pager | Print 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.service | Follow a service's new journal entries as they arrive. Press Ctrl+C to stop following. |
sudo journalctl -b -1 | Read the previous boot's logs if the journal retained them across reboots. |
sudo journalctl --since '1 hour ago' -p warning | Show warnings and more severe journal entries from the last hour. |
sudo dmesg --human | Read the kernel message buffer in a readable format, useful for hardware and driver errors. |
systemctl list-timers --all | List loaded systemd timers, including inactive ones, with their next and last runs. |
crontab -l | Show your user's recurring cron jobs. Requires cron or a compatible scheduler. |
crontab -e | Edit 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/COMMAND | Schedule 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
| Command | Explanation |
|---|---|
sudo apt update | Refresh package metadata from configured repositories. Installed packages are unchanged. |
apt list --upgradable | List installed packages with newer versions in the downloaded metadata. |
sudo apt upgrade | Install available package upgrades without removing installed packages. Review the proposed changes; updated services may restart. |
apt search TERM | Search package names and descriptions in the local repository metadata. |
apt show PACKAGE | Show a package's description, version, dependencies, and other metadata. |
sudo apt install PACKAGE | Install a package and its dependencies, or upgrade it if already installed. Package setup may start services. |
sudo apt remove PACKAGE | Remove a package while usually retaining its system configuration files. Review dependent packages proposed for removal. |
sudo apt purge PACKAGE | Remove a package and its managed system configuration. Files in users' home directories remain. |
sudo apt autoremove | Remove automatically installed packages that are no longer needed as dependencies. Review the list before confirming. |
Packages: DNF on Fedora and RHEL family
| Command | Explanation |
|---|---|
dnf check-update | Check available package updates with DNF 4. Exit status 100 indicates available updates; no packages are upgraded. |
dnf5 check-upgrade | Check available package updates with DNF 5. Exit status 100 indicates available updates; no packages are upgraded. |
dnf search TERM | Search package names and summaries in enabled repositories. |
dnf info PACKAGE | Show package versions, descriptions, and repository information. |
sudo dnf install PACKAGE | Install a package and its dependencies from enabled repositories. Review the transaction before accepting it. |
sudo dnf upgrade | Upgrade installed packages and resolve their dependencies. Updated services may need restarting, and a new kernel takes effect after reboot. |
sudo dnf remove PACKAGE | Remove a package and packages that depend on it. Review the removal list because related software may also be removed. |
rpm -qf /PATH/TO/FILE | Find the installed RPM package that owns a file. |
Disks, filesystems, and mounts
| Command | Explanation |
|---|---|
df -h | Show used and available space on mounted filesystems in readable units. |
df -i | Show inode usage. A filesystem can run out of inodes even when byte capacity remains. |
lsblk -f | Show block devices with filesystem types, labels, UUIDs, and mount points. |
sudo blkid | Probe block devices for filesystem identifiers, useful when configuring persistent mounts by UUID. |
findmnt --target /PATH | Identify the mounted filesystem containing a path and show its source and mount options. |
sudo fdisk -l | List disks and partition tables without changing them. |
sudo mount /dev/DEVICE /MOUNTPOINT | Mount 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 /MOUNTPOINT | Unmount a filesystem before disconnecting or checking it. Close files and leave directories on that mount first. |
sudo mkfs.ext4 /dev/DEVICE | Create an ext4 filesystem on the chosen unmounted device, destroying its previous filesystem data. Confirm the device with lsblk first. |
sudo e2fsck -f /dev/DEVICE | Check an ext2, ext3, or ext4 filesystem and ask before repairs. The filesystem must be unmounted; repairs modify it. |
sudo resize2fs /dev/DEVICE | Grow an ext filesystem to fill its already enlarged partition or logical volume. Online growth requires filesystem and kernel support. |
sudo xfs_growfs /MOUNTPOINT | Grow a mounted XFS filesystem after enlarging its underlying partition or logical volume. This command does not shrink XFS. |
du -sh DIRECTORY | Estimate 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 -h | Compare 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 +L1 | Find open files whose directory entries were deleted. Their disk space can remain occupied until the owning process closes the last handle. |
findmnt --verify --verbose | Check /etc/fstab for parsing and usability problems without mounting its entries. Useful before relying on edited mount configuration at reboot. |
Logical volumes and swap
| Command | Explanation |
|---|---|
sudo pvs | List LVM physical volumes and their volume-group membership. Requires the LVM tools. |
sudo vgs | Show LVM volume groups, total capacity, and free space for logical volumes. |
sudo lvs -o +devices | List logical volumes and the physical devices backing them. |
sudo pvcreate /dev/DEVICE | Initialize 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/DEVICE | Create a volume group from a prepared LVM physical volume that does not belong to another group. |
sudo lvcreate -L 10G -n LV_NAME VG_NAME | Allocate 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_NAME | Add 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 --show | List active swap devices and files with their sizes, usage, and priorities. |
sudo mkswap /dev/DEVICE | Format an unused partition or logical volume as swap, destroying its previous contents. This prepares the area but does not activate it. |
sudo swapon /dev/DEVICE | Activate a prepared swap device for this boot. Persistent activation needs a matching /etc/fstab entry. |
sudo swapoff /dev/DEVICE | Disable 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
| Command | Explanation |
|---|---|
ip -br address | Show network interfaces and assigned IPv4 and IPv6 addresses in a compact table. |
ip -s link | Show interface state and packet counters, including errors and dropped packets. |
ip route | Show the main IPv4 routing table, including the default gateway. |
ip route get IP_ADDRESS | Ask the kernel which route, interface, and source address it would use for a destination. |
ip neigh | Show neighboring hosts and cached link-layer addresses, including IPv4 ARP and IPv6 neighbor discovery entries. |
sudo ip link set dev INTERFACE up | Administratively 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 INTERFACE | Add 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 INTERFACE | Remove an interface address at runtime. Connections using that address can disconnect immediately. |
sudo ip route add NETWORK/PREFIX via GATEWAY dev INTERFACE | Add 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 INTERFACE | Remove the matching runtime route. Traffic that relied on it may stop reaching its destination. |
ping -c 4 HOST | Send four ICMP echo probes to test reachability and latency. Missing replies can also mean ICMP is filtered. |
tracepath HOST | Trace network hops and discover path MTU without root. Requires tracepath; routers may omit responses. |
sudo ss -lntup | Show listening TCP and UDP sockets with numeric addresses and owning processes. Elevated access reveals processes belonging to other users. |
ss -tn state established | List established TCP connections with numeric addresses and ports. |
getent ahosts HOST | Resolve a hostname through the system's configured name-service sources, including hosts files and DNS. |
resolvectl status | Show DNS servers and per-interface resolver settings when systemd-resolved is in use. |
dig HOST A +short | Query 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 AAAA | Query a specific DNS server for IPv6 records, showing the response status and answer details. |
nc -vz -w 3 HOST PORT | With 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 route | Show IPv6 routes, including the IPv6 default gateway. IPv4 and IPv6 maintain separate routing tables. |
HTTP and TLS diagnostics
| Command | Explanation |
|---|---|
curl -I https://HOST | Send an HTTP HEAD request and show response headers. Some servers handle HEAD differently from GET. |
curl --fail --location --output FILE https://HOST/PATH | Download a URL, following redirects and failing on HTTP errors. The output file is created or overwritten. |
curl -v https://HOST | Show 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/null | Inspect 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
| Command | Explanation |
|---|---|
sudo ufw status numbered | Show UFW's status and numbered rules on a host managed by UFW. |
sudo ufw allow PORT/tcp | Add a persistent UFW rule allowing inbound TCP traffic to a port. It takes effect immediately if UFW is enabled. |
sudo ufw enable | Enable 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_NUMBER | Remove 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-zones | On a firewalld host, show which zones are assigned to interfaces or source addresses. |
sudo firewall-cmd --zone=ZONE --list-all | Show the runtime services, ports, and other settings of a firewalld zone. |
sudo firewall-cmd --permanent --zone=ZONE --add-port=PORT/tcp | Allow an inbound TCP port in a zone's saved firewalld configuration. The change takes effect after reload or restart. |
sudo firewall-cmd --reload | Replace firewalld's runtime settings with its saved configuration. Runtime-only changes are normally lost, so confirm saved SSH access first. |
sudo nft list ruleset | Inspect the active nftables ruleset, including rules created by a firewall manager using nftables. |
SSH, SCP, and rsync
| Command | Explanation |
|---|---|
ssh USER@HOST | Open 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@HOST | Connect to a non-default SSH port using a specific private key. The server must authorize the corresponding public key. |
ssh -v USER@HOST | Print SSH connection and authentication diagnostics to investigate login failures. |
ssh-keygen -t ed25519 -f ~/.ssh/KEY_NAME | Generate 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@HOST | Install 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_HOST | Forward 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@TARGET | Reach 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_KEY | Load 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
| Command | Explanation |
|---|---|
git clone URL | Download a repository and its history into a new local directory. |
git status --short | See changed, staged, and untracked files before committing. The left status column describes the staging area; the right describes the working tree. |
git diff | Show tracked changes that have not been staged. New, untracked files are not included. |
git diff --staged | Review exactly the changes currently staged for the next commit. |
git add FILE | Stage 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 -20 | Show the latest 20 commits reachable from all refs, including branch tips, as a compact graph. |
git show COMMIT | Inspect a commit's message and patch; replace COMMIT with its hash or a reference such as HEAD. |
git switch -c BRANCH | Create a new branch from the current commit and switch to it. |
git switch BRANCH | Switch to an existing branch. Git refuses if switching would overwrite conflicting local changes. |
git fetch origin | Download new remote commits and update remote-tracking references without merging into your branch. |
git pull --ff-only | Fetch and update the current branch only when no merge commit is needed. It stops if local and remote histories have diverged. |
git merge BRANCH | Integrate another branch into the current one. Conflicting edits must be resolved before completing the merge. |
git push -u origin BRANCH | Upload the branch and set origin/BRANCH as its upstream for later pulls and pushes. |
git restore --staged FILE | Remove a file's changes from the staging area while keeping them in the working tree. |
git restore FILE | Discard unstaged edits in a tracked file by restoring its staged version. Those discarded edits are not automatically recoverable. |
git revert COMMIT | Create 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 pop | Reapply the most recent stash and remove it if application succeeds; conflicts leave the stash available. |
git remote -v | Show remote names and their fetch/push URLs to check which repository you are using. |
git reflog | Show recent local movements of HEAD, useful for finding commits after a mistaken reset or branch change. |
Docker: images and containers
| Command | Explanation |
|---|---|
docker version | Show Docker client and server versions. A missing server response often means the daemon is unavailable or inaccessible. |
docker context ls | List Docker connection contexts and identify the active daemon; commands can target a remote machine. |
docker pull IMAGE:TAG | Download 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 ls | List images stored in the selected Docker daemon, including tags and sizes. |
docker run --rm -it --entrypoint sh IMAGE:TAG | Start 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:TAG | Run a container in the background and publish its port 80 on host port 8080, accessible only through the host's loopback interface. |
docker ps -a | List running and stopped containers. Without -a, only running containers are shown. |
docker logs --tail 100 -f CONTAINER | Show 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 sh | Open another shell inside an already running container. This does not start a new container, and the image must contain sh. |
docker inspect CONTAINER | Show detailed container configuration, mounts, networks, and state as JSON. The output can include environment secrets. |
docker stats | Watch CPU, memory, network, and disk I/O usage for running containers. |
docker stop CONTAINER | Request a graceful stop, then force termination if the container does not exit within the stop timeout. |
docker start CONTAINER | Start an existing stopped container with its previous configuration and writable layer. |
docker rm CONTAINER | Remove a stopped container and its writable layer. Named volumes remain until explicitly removed. |
docker volume create DATA | Create a named volume whose data can outlive the containers that mount it. |
docker run -d --mount type=volume,src=DATA,dst=/data IMAGE:TAG | Mount a named volume at /data in a new container. Data written there is stored outside the container's writable layer. |
docker network create NETWORK | Create a user-defined bridge network for local containers, including name-based discovery between attached containers. |
docker network inspect NETWORK | Inspect a Docker network and the containers connected to it. |
docker login REGISTRY | Authenticate to a registry using the supported interactive flow. Prefer a configured credential helper to plaintext credential storage. |
docker tag IMAGE:TAG REGISTRY/REPOSITORY:TAG | Add another reference to an existing local image so it can be pushed to the intended registry and repository. |
docker push REGISTRY/REPOSITORY:TAG | Upload an image to a registry; requires permission to write to that repository. |
docker system df | Show disk space used by images, containers, volumes, and the build cache before deciding what to remove. |
docker image prune | Remove dangling images after confirmation. It does not remove every unused tagged image unless -a is added. |
Docker Compose: multiple services
| Command | Explanation |
|---|---|
docker compose config --quiet | Validate the Compose configuration without printing its resolved contents. Run in the project directory or supply -f FILE. |
docker compose up -d --build | Build images as needed, create or recreate services, and run them in the background. |
docker compose ps | List the project's containers, status, and published ports. |
docker compose logs -f SERVICE | Follow logs for one Compose service; omit SERVICE to follow all services in the project. |
docker compose exec SERVICE sh | Open a shell in a running service container, provided its image contains sh. |
docker compose pull | Fetch service images from registries. Running containers keep their old images until recreated. |
docker compose down | Stop 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
| Command | Explanation |
|---|---|
kubectl version | Show client and API server versions. Reaching the server requires a working kubeconfig and network access. |
kubectl config get-contexts | List configured clusters, users, and default namespaces. The asterisk marks the context kubectl uses by default. |
kubectl config current-context | Check the active context before changing cluster resources. A context selects the cluster and credentials, not just a namespace. |
kubectl config use-context CONTEXT | Change the active context for subsequent kubectl commands. |
kubectl config set-context --current --namespace=NAMESPACE | Set the default namespace in the current context. An explicit -n on a command overrides it. |
kubectl --context=CONTEXT -n NAMESPACE get pods | Target a specific context and namespace for one command without changing the defaults. |
kubectl cluster-info | Show the API server address and discovered cluster service endpoints. This is a quick connectivity check, not a full health assessment. |
kubectl api-resources | List resource kinds supported by this cluster, their short names, API groups, and whether they belong to a namespace. |
kubectl explain deployment.spec.template.spec.containers | Look up the schema for a Deployment's container definitions before writing YAML. |
kubectl get namespaces | List namespaces, which organize namespaced resources within the same cluster. |
kubectl create namespace NAMESPACE | Create a namespace. It does not automatically provide network isolation or permissions for users. |
kubectl get nodes -o wide | List nodes with readiness, roles, versions, and addresses. Nodes are cluster-scoped, so -n does not apply. |
kubectl get pods -A | List 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 wide | Show pods in one namespace with their IP addresses and assigned nodes. |
kubectl get pods -n NAMESPACE -l app=APP | Filter pods by a label. This matches the app label's value, not the pod name. |
kubectl get pods -n NAMESPACE --watch | Print pod changes as they happen; Ctrl+C ends the watch without affecting the pods. |
Kubernetes: manifests and workloads
| Command | Explanation |
|---|---|
kubectl apply --dry-run=server -f FILE | Ask the API server to validate a manifest and run dry-run admission checks without saving the resource. Requires server access. |
kubectl diff -f FILE | Compare a manifest's intended state with the live resources before applying it. Exit code 1 means differences were found. |
kubectl apply -f FILE | Create 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 DIRECTORY | Build and apply a directory's Kustomize configuration, including its patches and overlays. |
kubectl kustomize DIRECTORY | Render a Kustomize directory as YAML without applying it, so you can inspect the combined manifests. |
kubectl get deployment APP -n NAMESPACE -o yaml | Inspect 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 yaml | Generate a starter Deployment manifest locally; it is printed, not created in the cluster. |
kubectl rollout status deployment/APP -n NAMESPACE --timeout=120s | Wait up to two minutes for a Deployment rollout to finish, useful after applying a change. |
kubectl set image deployment/APP CONTAINER=IMAGE:TAG -n NAMESPACE | Update 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 NAMESPACE | Set 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 NAMESPACE | Trigger replacement pods using the Deployment's rollout strategy, for example to reload configuration read only at startup. |
kubectl rollout history deployment/APP -n NAMESPACE | List retained Deployment revisions to investigate an update or choose a rollback target. |
kubectl rollout undo deployment/APP -n NAMESPACE | Restore the previous retained pod-template revision. This does not undo external database changes or every Deployment setting. |
kubectl get deployments,statefulsets,daemonsets -n NAMESPACE | Compare desired and ready replicas across the main workload controllers. A DaemonSet normally runs a pod on each eligible node. |
kubectl get jobs,cronjobs -n NAMESPACE | Inspect one-off jobs and scheduled jobs, including completion counts and scheduling status. |
kubectl create job JOB --from=cronjob/CRONJOB -n NAMESPACE | Start 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 FILE | Delete 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 NAMESPACE | Open 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=60s | Wait 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 NAMESPACE | Create 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 NAMESPACE | Set 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 NAMESPACE | Attach 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
| Command | Explanation |
|---|---|
kubectl create configmap CONFIG --from-file=FILE -n NAMESPACE | Create 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 NAMESPACE | Create 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 NAMESPACE | List configuration objects and Secret metadata without printing their data values. |
kubectl get services -n NAMESPACE | Show 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 NAMESPACE | Create 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 yaml | Inspect a Service's backend addresses and readiness conditions in YAML to investigate routing problems. |
kubectl port-forward service/SERVICE 8080:80 -n NAMESPACE | Forward 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 NAMESPACE | Inspect HTTP routing rules and assigned addresses. An installed Ingress controller must implement those rules. |
kubectl get gateways,httproutes -n NAMESPACE | Inspect Gateway API entry points and routes. Requires Gateway API resources and a compatible controller to be installed. |
kubectl get networkpolicies -n NAMESPACE | List network restrictions defined for pods. Enforcement depends on the cluster's networking plugin supporting NetworkPolicy. |
kubectl get pvc -n NAMESPACE | List PersistentVolumeClaims and their binding state; Pending often indicates a provisioning or matching problem. |
kubectl get pv,storageclasses | Inspect cluster-wide volumes and storage provisioning classes, including reclaim policies and provisioners. |
kubectl describe pvc CLAIM -n NAMESPACE | Read a claim's storage requirements, binding information, and events to investigate a failed volume allocation. |
kubectl describe resourcequotas,limitranges -n NAMESPACE | Inspect namespace-wide resource budgets and default or allowed container resource values. |
kubectl get hpa -n NAMESPACE | Inspect HorizontalPodAutoscalers and their current versus target metrics. Metrics collection must be available for scaling to work. |
Kubernetes: troubleshooting
| Command | Explanation |
|---|---|
kubectl describe pod POD -n NAMESPACE | Read 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=100 | Read 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 --previous | Read 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=-1 | Collect 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 -- sh | Run 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 CONTAINER | Copy a file from a container to the local machine. kubectl cp requires tar inside the container. |
kubectl get events -n NAMESPACE --sort-by=.metadata.creationTimestamp | List events in creation order to spot failed scheduling, image pulls, and volume mounts. Events have limited retention. |
kubectl top pods -n NAMESPACE --containers | Show recent CPU and memory usage per container. Requires the resource metrics API, usually supplied by Metrics Server. |
kubectl top nodes | Compare 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 NAMESPACE | Add 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=NODE | Find all pods scheduled on a particular node, useful before maintenance or when investigating node failures. |
Kubernetes: access and security
| Command | Explanation |
|---|---|
kubectl auth can-i create deployments -n NAMESPACE | Ask whether your current identity is authorized to create Deployments in the namespace. |
kubectl auth can-i --list -n NAMESPACE | List allowed actions in a namespace for the current identity; authorization plugins can limit how complete this list is. |
kubectl get roles,rolebindings -n NAMESPACE | Inspect namespace-level RBAC roles and the bindings assigning those permissions to identities. |
kubectl get clusterroles,clusterrolebindings | Inspect cluster-wide role definitions and bindings. A ClusterRoleBinding grants permissions across the cluster. |
kubectl create serviceaccount SERVICEACCOUNT -n NAMESPACE | Create 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 NAMESPACE | Define 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 NAMESPACE | Grant 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 --overwrite | Enforce 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
| Command | Explanation |
|---|---|
helm repo add REPO HTTPS_URL | Register a Helm chart repository under a local name. This does not install anything into a cluster. |
helm repo update | Refresh indexes of configured chart repositories so searches see current chart versions. |
helm search repo REPO/CHART --versions | List chart versions in local repository indexes. The chart version and application version can differ. |
helm show values REPO/CHART | Inspect a chart's default configuration before writing your own values file. |
helm lint CHART_DIRECTORY | Check 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_FILE | Render 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 5m | Install 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 -A | List Helm releases across all namespaces. This requires cluster-wide access to the configured release storage, normally Secrets. |
helm status RELEASE -n NAMESPACE | Inspect a release's state, revision, and chart notes after installation or an upgrade. |
helm history RELEASE -n NAMESPACE | List release revisions so you can identify a previous deployment to roll back to. |
helm rollback RELEASE REVISION -n NAMESPACE --wait | Restore a retained release revision. This does not reverse application-level data migrations. |
helm uninstall RELEASE -n NAMESPACE | Remove a Helm release and its managed resources. Persistent data and hook resources can have separate retention behavior. |
Kubernetes: node and cluster administration
| Command | Explanation |
|---|---|
kubectl describe node NODE | Inspect 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 wide | Inspect system pods such as DNS and networking components. Managed services may hide control-plane components. |
kubectl get pdb -A | Review PodDisruptionBudgets and allowed disruptions before draining nodes. These budgets constrain voluntary evictions, not hardware failures. |
kubectl cordon NODE | Mark a node unschedulable for ordinary new pods. Existing pods keep running. |
kubectl drain NODE --ignore-daemonsets --timeout=10m | Cordon 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 NODE | Allow 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 --overwrite | Set 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:NoSchedule | Prevent 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 crd | List CustomResourceDefinitions, which extend the cluster API with additional resource types used by operators and other tools. |
sudo journalctl -u kubelet -n 100 --no-pager | On a Linux node using systemd, inspect recent kubelet logs when pods cannot start or the node becomes NotReady. |
sudo crictl ps -a | On 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_ID | Read a node-local container's logs through the CRI runtime, useful when kubectl logs cannot reach the node. |
sudo crictl images | List 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
| Command | Explanation |
|---|---|
sudo kubeadm init --config CLUSTER_CONFIG | Bootstrap 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-command | On 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:HASH | Join 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 plan | Check supported upgrades for a self-managed kubeadm cluster. Follow the version-specific procedure; Kubernetes minor versions must not be skipped. |
sudo kubeadm upgrade apply VERSION | Perform 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 node | Apply 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-expiration | Inspect expiry dates of certificates managed by kubeadm on a control-plane node. Externally managed certificates need their own renewal process. |
sudo kubeadm certs renew all | Renew 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 health | Check 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.db | Save 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=table | Inspect 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_DIRECTORY | Build 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. |