🖥️ Linux CPU & Memory Performance
CPU Overview
CPU Detail
Memory
Processes
Load & Scheduler
I/O & Disk
Profiling
Tuning

CPU usage — quick overview

top 📄 docs Real-time view of CPU usage, load average, and top processes
Examples
top
# Interactive real-time view
top -d 1
# Refresh every 1 second
top -p 1234
# Monitor specific PID
top -u www-data
# Filter by user
top -b -n 1
# Batch mode, single snapshot (good for scripts)
Key shortcuts inside top
P
# Sort by CPU usage
M
# Sort by memory usage
1
# Toggle per-CPU breakdown
k
# Kill a process by PID
q
# Quit
htop recommended 📄 docs Enhanced interactive process viewer with color, graphs, and mouse support
Examples
htop
# Interactive view (install: apt install htop)
htop -u postgres
# Filter by user
htop -p 1234,5678
# Monitor specific PIDs
htop -d 5
# Refresh delay in tenths of a second
Key shortcuts inside htop
F6
# Sort by column
F5
# Toggle tree view (process hierarchy)
F4
# Filter processes by name
Space
# Tag process (multi-select)
F9
# Send signal to process
uptime 📄 docs System uptime and 1/5/15-minute load averages at a glance
Examples
uptime
# Load avg: 1, 5, 15 min — compare to CPU count
uptime -p
# Human-readable uptime only
cat /proc/loadavg
# Raw load avg + running/total threads
vmstat 📄 docs System-wide CPU, memory, swap, I/O, and context switch stats
Examples
vmstat 1
# Update every second (first row = since boot)
vmstat 1 10
# 10 samples, 1 second apart
vmstat -s
# Summary statistics table
vmstat -d
# Disk statistics
Key columns to watch
r
# Processes waiting for CPU (run queue) — high = CPU saturation
b
# Processes in uninterruptible sleep (I/O wait)
cs
# Context switches per second
us sy id wa
# user / system / idle / I/O wait %
sar recommended 📄 docs System Activity Reporter — historical CPU, memory, I/O data (sysstat package)
Examples
sar 1 5
# CPU stats every 1s for 5 samples
sar -u 1 5
# CPU utilization
sar -r 1 5
# Memory utilization
sar -q 1 5
# Run queue and load average
sar -f /var/log/sysstat/sa01
# Read historical data from file
sar -A
# All metrics
glances recommended 📄 docs All-in-one monitoring dashboard: CPU, memory, I/O, network in one screen
Examples
glances
# Full dashboard (install: pip install glances)
glances --web
# Web interface on port 61208
glances -t 2
# Refresh interval 2 seconds
glances --export csv --export-csv-file /tmp/perf.csv

CPU detail — per-core, frequency, topology

mpstat 📄 docs Per-CPU utilization breakdown — spot unbalanced load across cores
Examples
mpstat -P ALL 1
# All CPUs, 1-second interval
mpstat -P 0,1,2 1
# Only cores 0, 1, 2
mpstat 1 5
# Aggregate (all CPUs), 5 samples
mpstat -I ALL 1
# Per-CPU interrupt statistics
lscpu 📄 docs CPU topology: sockets, cores, threads, NUMA, cache sizes
Examples
lscpu
# Full CPU info: model, cores, threads, NUMA
lscpu -e
# Per-CPU extended info (CPU, core, socket, NUMA node)
lscpu --json
# JSON output for scripting
cat /proc/cpuinfo
# Raw per-core CPU info from kernel
nproc
# Number of processing units available
cpufreq-info / cpupower 📄 docs CPU frequency scaling: current freq, governor, min/max limits
Examples
cpupower frequency-info
# Current freq and governor for all CPUs
cpupower frequency-set -g performance
# Set performance governor
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq
# Current freq per core
turbostat --interval 1
# Per-core freq, C-states, power (Intel)
pidstat 📄 docs Per-process CPU, memory, I/O stats — like top but scriptable
Examples
pidstat 1
# All active processes, 1-second interval
pidstat -p 1234 1
# Single process by PID
pidstat -u -r -d 1
# CPU + memory + disk for all processes
pidstat -t 1
# Per-thread stats
pidstat -C nginx 1
# Filter by process name
taskset / numactl 📄 docs Pin processes to specific CPUs or NUMA nodes for performance isolation
Examples
taskset -cp 1234
# Show CPU affinity of PID 1234
taskset -cp 0,1 1234
# Pin PID 1234 to cores 0 and 1
taskset -c 2 ./myapp
# Launch app pinned to core 2
numactl --hardware
# Show NUMA topology
numactl --cpunodebind=0 --membind=0 ./myapp
# Run on NUMA node 0
stress / stress-ng advanced 📄 docs Generate synthetic CPU/memory/I/O load for testing and benchmarking
Examples
stress --cpu 4 --timeout 30
# Load 4 CPU workers for 30s
stress-ng --cpu 0 --cpu-method matrixprod -t 60s
# All cores, matrix multiply
stress-ng --vm 2 --vm-bytes 1G -t 30s
# 2 workers, 1G memory each
stress-ng --metrics-brief --cpu 4 -t 10s
# With performance metrics

Memory usage and analysis

free 📄 docs Quick summary of RAM and swap usage — most common first check
Examples
free -h
# Human-readable (GB/MB)
free -m
# In megabytes
free -s 2
# Refresh every 2 seconds
watch -n 1 free -h
# Continuous watch
Reading the output
available
# Memory actually usable by new processes (most important)
buff/cache
# Kernel cache — reclaimable if needed, not a problem
Swap used > 0
# Warning: RAM pressure, kernel is swapping
/proc/meminfo 📄 docs Detailed kernel memory breakdown: huge pages, slabs, page tables
Examples
cat /proc/meminfo
# Full memory map from kernel
grep -i huge /proc/meminfo
# Huge pages info
grep -E 'MemFree|MemAvail|SwapUsed|Dirty' /proc/meminfo
grep Slab /proc/meminfo
# Kernel slab allocator usage
pmap 📄 docs Memory map of a process — see shared libs, heap, stack sizes
Examples
pmap 1234
# Memory map of PID 1234
pmap -x 1234
# Extended output (RSS, dirty pages)
pmap -d 1234
# Device format
pmap -x 1234 | tail -1
# Total RSS for the process
smem recommended 📄 docs Accurate per-process memory: USS, PSS, RSS accounting for shared memory
Examples
smem -r
# Sort by RSS descending
smem -s pss -r
# Sort by PSS (proportional set size)
smem -u
# Aggregate per user
smem -P nginx
# Filter by process name
smem --pie name -s rss
# Pie chart by process name
Key metrics
USS
# Unique Set Size — memory only this process uses
PSS
# Proportional Set Size — most accurate for total usage
RSS
# Resident Set Size — inflated if sharing lots of libs
slabtop 📄 docs Kernel slab cache usage in real time — diagnose kernel memory leaks
Examples
slabtop
# Interactive slab cache viewer
slabtop -s c
# Sort by cache size
cat /proc/slabinfo
# Raw slab data
slabtop -o
# One-shot output (non-interactive)
valgrind / heaptrack advanced 📄 docs Detect memory leaks, invalid accesses, and heap profiling in applications
Examples
valgrind --leak-check=full ./myapp
# Full memory leak report
valgrind --tool=massif ./myapp
# Heap profiling
ms_print massif.out.* | head -30
# Analyze massif output
heaptrack ./myapp
# Fast heap profiler (lighter than valgrind)
heaptrack_print heaptrack.myapp.*.gz
# Print heap analysis
swap diagnostics 📄 docs Identify what is using swap and how to reduce pressure
Examples
swapon --show
# Show all swap devices and usage
cat /proc/*/status | grep -E 'Name|VmSwap' | paste - -
# Swap per process
cat /proc/sys/vm/swappiness
# Current swappiness (default 60)
sysctl -w vm.swappiness=10
# Reduce swapping aggressiveness
swapoff -a && swapon -a
# Flush swap (WARNING: needs enough free RAM)

Process inspection and management

ps 📄 docs Snapshot of running processes with configurable columns
Examples
ps aux
# All processes, BSD style
ps aux --sort=-%cpu | head -10
# Top 10 by CPU
ps aux --sort=-%mem | head -10
# Top 10 by memory
ps -eo pid,ppid,cmd,%cpu,%mem --sort=-%cpu
# Custom columns
ps -ef | grep nginx
# Full format, filter by name
ps -p 1234 -o pid,vsz,rss,pmem,comm
# Memory info for PID
pgrep / pkill 📄 docs Find or signal processes by name, user, or other criteria
Examples
pgrep nginx
# PIDs of all nginx processes
pgrep -u postgres
# PIDs owned by user postgres
pgrep -la python
# PIDs and full command lines
pkill -9 zombie_app
# Force kill by name
pkill -u olduser
# Kill all processes by user
nice / renice 📄 docs Set or change process scheduling priority (-20 highest, 19 lowest)
Examples
nice -n 10 ./batch_job.sh
# Launch with lower priority
nice -n -5 ./realtime_app
# Higher priority (requires root)
renice -n 15 -p 1234
# Lower priority of running process
renice -n -10 -u postgres
# Raise priority for all postgres processes
ps -eo pid,ni,comm | grep -v " 0 "
# Show non-default niceness
strace advanced 📄 docs Trace system calls made by a process — diagnose hangs and slowdowns
Examples
strace -p 1234
# Attach to running process
strace -p 1234 -e trace=open,read,write
# Filter syscalls
strace -c ./myapp
# Count syscalls and show summary
strace -T -p 1234
# Show time spent in each syscall
strace -f -p 1234
# Follow child processes (fork)
lsof 📄 docs List open files, sockets, pipes for any process
Examples
lsof -p 1234
# All open files for PID 1234
lsof -p 1234 | wc -l
# Count open file descriptors
lsof -u postgres
# All files opened by postgres user
lsof /var/log/app.log
# Which process has this file open
cat /proc/sys/fs/file-nr
# System-wide file descriptor usage

Load average and CPU scheduler

w / who 📄 docs Logged-in users and their current load contributions
Examples
w
# Who is logged in and what they're running
who -b
# Last system boot time
last reboot | head -5
# Recent reboots
chrt 📄 docs Get or set real-time scheduling policy for a process (SCHED_FIFO, RR)
Examples
chrt -p 1234
# Show scheduling policy of PID 1234
chrt -f -p 50 1234
# Set SCHED_FIFO priority 50 (requires root)
chrt -r 10 ./realtime_app
# Launch with SCHED_RR priority 10
chrt -o -p 0 1234
# Set SCHED_OTHER (normal CFS)
schedtool advanced 📄 docs Query and set CPU affinity and scheduling parameters
Examples
schedtool 1234
# Show scheduling info for PID
schedtool -B 1234
# Set SCHED_BATCH (background batch job)
schedtool -I -p 20 1234
# SCHED_FIFO real-time priority 20
cgroups (cgroup v2) 📄 docs Limit and account CPU/memory usage per group of processes
Examples
systemctl status user.slice
# cgroup usage via systemd
systemd-cgtop
# Real-time cgroup resource usage
cat /sys/fs/cgroup/memory.current
# Current memory usage of cgroup
cat /sys/fs/cgroup/cpu.stat
# CPU usage stats of cgroup
systemctl set-property myservice.service CPUQuota=50%
# Limit service to 50% CPU
systemctl set-property myservice.service MemoryMax=512M
irqbalance / /proc/interrupts 📄 docs Inspect and balance hardware interrupt distribution across CPUs
Examples
cat /proc/interrupts
# IRQ counts per CPU
watch -n 1 'cat /proc/interrupts | head -20'
systemctl status irqbalance
# Is IRQ balancing active?
cat /proc/softirqs
# Software interrupt stats per CPU

I/O and disk performance

iostat recommended 📄 docs Per-device I/O throughput, utilization, and wait times
Examples
iostat -x 1
# Extended stats every second (key command)
iostat -x 1 5
# 5 samples
iostat -d sda 1
# Only device sda
iostat -h 1
# Human-readable units
Key columns
%util
# Disk utilization — near 100% = saturated
await
# Average I/O wait time (ms) — high = slow disk or queuing
r/s w/s
# Read/write operations per second
rMB/s wMB/s
# Throughput in MB/s
iotop recommended 📄 docs Top-like view of disk I/O per process — find I/O-heavy processes instantly
Examples
iotop
# Interactive I/O monitor (requires root)
iotop -o
# Show only processes doing I/O
iotop -b -n 5
# Batch mode, 5 iterations
iotop -p 1234
# Single process
iotop -u postgres
# Filter by user
fio advanced 📄 docs Flexible I/O benchmarking — test sequential, random, and mixed workloads
Examples
fio --name=randread --rw=randread --bs=4k --size=1G --numjobs=4
fio --name=seqwrite --rw=write --bs=1M --size=2G
# Sequential write
fio --name=randrw --rw=randrw --bs=4k --size=512M --rwmixread=70
# 70% read mixed
fio --name=latency --rw=randread --bs=512 --iodepth=1 --size=256M
dd 📄 docs Quick sequential read/write speed test — simple but effective baseline
Examples
dd if=/dev/zero of=/tmp/test bs=1M count=1024 oflag=direct
# Write speed (direct I/O)
dd if=/tmp/test of=/dev/null bs=1M iflag=direct
# Read speed
dd if=/dev/urandom of=/tmp/test bs=1M count=256 status=progress
blktrace / blkparse advanced 📄 docs Block I/O tracing — see exact I/O requests, queuing, and dispatch times
Examples
blktrace -d /dev/sda -o trace
# Capture block trace
blkparse -i trace -d trace.bin
# Parse trace
btt -i trace.bin
# Block trace analysis (latency, queue depth)
cat /sys/block/sda/queue/scheduler
# Current I/O scheduler
echo mq-deadline > /sys/block/sda/queue/scheduler
# Change scheduler

CPU profiling and eBPF tracing

perf advanced 📄 docs Linux performance counter tool — CPU cycles, cache misses, function profiling
Examples
perf top
# Live CPU hotspots (like top for functions)
perf record -g ./myapp
# Record with call graph
perf report
# Interactive report from perf.data
perf stat ./myapp
# Hardware counters: cycles, instructions, cache misses
perf stat -e cache-misses,cache-references ./myapp
perf record -F 99 -p 1234 -g -- sleep 10
# Sample at 99Hz for 10s
FlameGraph 📄 docs Visualize perf profiles as interactive flame graphs (Brendan Gregg)
Examples
perf record -F 99 -a -g -- sleep 30
# Capture all CPUs for 30s
perf script > out.perf
stackcollapse-perf.pl out.perf > out.folded
flamegraph.pl out.folded > flamegraph.svg
# Open SVG in browser
bpftrace advanced 📄 docs High-level eBPF tracing language for custom kernel and userspace probes
Examples
bpftrace -e 'profile:hz:99 { @[comm] = count(); }'
# CPU time per process (sampling)
bpftrace -e 'kprobe:do_sys_open { printf("%s %s\n", comm, str(arg1)); }'
# Trace file opens
bpftrace -e 'tracepoint:sched:sched_switch { @[prev_comm] = count(); }'
# Context switches per process
bpftrace /usr/share/bpftrace/tools/runqlat.bt
# Run queue latency histogram
BCC tools advanced 📄 docs Pre-built eBPF tools from BPF Compiler Collection (BCC)
Examples
runqlat
# Scheduler run queue latency histogram
cpudist
# On-CPU time distribution per process
offcputime -p 1234 10
# Off-CPU time (blocking) for PID, 10s
biolatency
# Block I/O latency histogram
cachestat 1
# Page cache hit/miss stats
memleak -p 1234
# Detect memory leaks in process
funclatency 'do_sys_open' 1
# Latency histogram for a kernel function
gprof / callgrind 📄 docs Application-level profiling — find hotspots in your own code
Examples
gcc -pg -o myapp myapp.c && ./myapp && gprof myapp gmon.out
valgrind --tool=callgrind ./myapp
# Detailed call graph profiling
callgrind_annotate callgrind.out.*
# Annotated source with costs
kcachegrind callgrind.out.*
# GUI viewer for callgrind output

Kernel tuning and system limits

sysctl (CPU/memory) 📄 docs Key kernel parameters that affect CPU and memory performance
Memory parameters
sysctl vm.swappiness
# Swap aggressiveness (0-100, lower = prefer RAM)
sysctl vm.dirty_ratio
# % RAM for dirty pages before forced writeback
sysctl vm.dirty_background_ratio
# % RAM for background writeback start
sysctl vm.overcommit_memory
# 0=heuristic, 1=always, 2=never
sysctl -w vm.drop_caches=3
# Drop page/slab/inode caches (testing only)
CPU/scheduler parameters
sysctl kernel.sched_min_granularity_ns
# CFS min scheduling granularity
sysctl kernel.sched_migration_cost_ns
# Cost to migrate task between CPUs
sysctl kernel.pid_max
# Max PID value (default 32768)
sysctl kernel.perf_event_paranoid
# perf access level (0=all, 2=restricted)
ulimit 📄 docs Per-process resource limits: file descriptors, stack size, max memory
Examples
ulimit -a
# Show all limits for current shell
ulimit -n
# Max open file descriptors
ulimit -n 65536
# Increase FD limit for current session
ulimit -s
# Stack size limit
ulimit -v $((2*1024*1024))
# Limit virtual memory to 2GB
cat /proc/1234/limits
# Limits of a specific running process
hugepages 📄 docs Configure huge pages to reduce TLB pressure for memory-intensive apps
Examples
grep -i huge /proc/meminfo
# Current huge page usage
cat /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
echo 512 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
# Reserve 512 x 2MB pages
cat /sys/kernel/mm/transparent_hugepage/enabled
# THP status
echo never > /sys/kernel/mm/transparent_hugepage/enabled
# Disable THP (DBs often prefer this)
numastat / numactl 📄 docs NUMA memory allocation stats — detect cross-node memory access penalties
Examples
numastat
# NUMA hit/miss stats per node
numastat -m
# Memory usage per NUMA node
numastat -p 1234
# NUMA stats for specific process
numactl --hardware
# NUMA topology and distances
numactl --interleave=all ./myapp
# Interleave memory across NUMA nodes
tuned / tuned-adm 📄 docs Apply pre-built tuning profiles (latency, throughput, power-save)
Examples
tuned-adm list
# Available profiles
tuned-adm active
# Currently active profile
tuned-adm profile throughput-performance
# High-throughput servers
tuned-adm profile latency-performance
# Low-latency applications
tuned-adm profile powersave
# Battery / energy saving
tuned-adm recommend
# Recommend profile for this hardware
OOM killer diagnostics 📄 docs Understand and control how the kernel kills processes under memory pressure
Examples
dmesg | grep -i 'oom\|killed process'
# Find OOM kills in kernel log
journalctl -k | grep -i oom
# OOM events via journald
cat /proc/1234/oom_score
# OOM score of a process (higher = more likely to be killed)
echo -17 > /proc/1234/oom_score_adj
# Protect process from OOM killer
echo 1000 > /proc/1234/oom_score_adj
# Make process OOM-killed first
sysctl -w vm.panic_on_oom=0
# Don't panic on OOM, let killer run
🐧 Linux Network Troubleshooting
Interfaces
Connectivity
DNS
Ports
Routes
Traffic
Firewall
Logs
VPN/Tunnels
Net Performance
Wi-Fi

Network interfaces

ip a 📄 docs Shows all interfaces with IPs, state and MAC address
Examples
ip a
# All interfaces
ip a show eth0
# Only eth0 interface
ip -4 a
# IPv4 only
ip -6 a
# IPv6 only
ip link 📄 docs Interface state (UP/DOWN), MTU, flags
Examples
ip link show
ip link set eth0 up
# Bring interface up
ip link set eth0 down
ip link set eth0 mtu 9000
# Change MTU (jumbo frames)
ifconfig deprecated 📄 docs Classic alternative to ip a (net-tools package)
Examples
ifconfig
ifconfig eth0
ifconfig eth0 up
ethtool 📄 docs Speed, duplex, driver state and NIC hardware info
Examples
ethtool eth0
# General info (speed, link detected)
ethtool -i eth0
# Driver info
ethtool -S eth0
# Driver statistics
ethtool -t eth0
# Hardware self-test
ip addr add/del 📄 docs Add or remove IP addresses on an interface
Examples
ip addr add 192.168.1.100/24 dev eth0
ip addr del 192.168.1.100/24 dev eth0
ip addr flush dev eth0
# Flush all IPs from interface
nmcli recommended 📄 docs Full network management with NetworkManager from CLI
Examples
nmcli device status
# Status of all devices
nmcli connection show
# Saved connections
nmcli device connect eth0
nmcli networking off
# Disable all networking
nmcli general status
lshw -class network 📄 docs Detailed info on installed network hardware
Examples
lshw -class network
# NIC info (requires root)
lshw -class network -short
# Short format
lspci | grep -i net
# List PCI network cards
lsusb | grep -i net
# List USB network adapters

Verify connectivity

ping 📄 docs Check reachability and latency to a host
Examples
ping 8.8.8.8
# Ping Google DNS (internet)
ping -c 4 192.168.1.1
# Only 4 packets
ping -i 0.2 -s 1400 host
# Custom interval and packet size
ping6 ::1
# IPv6 loopback ping
traceroute 📄 docs Trace the packet route to destination, hop by hop
Examples
traceroute google.com
traceroute -n 8.8.8.8
# Skip DNS resolution (faster)
traceroute -T -p 80 google.com
# Using TCP on port 80
traceroute6 ipv6.google.com
mtr recommended 📄 docs Combines ping + traceroute in real time. Great for diagnosing packet loss
Examples
mtr 8.8.8.8
# Interactive mode
mtr --report google.com
# Report mode (non-interactive)
mtr -n --report-cycles 100 8.8.8.8
# 100 cycles without DNS
curl / wget 📄 docs Check HTTP/HTTPS connectivity at the application level
Examples
curl -I https://google.com
# Headers only
curl -v --resolve google.com:443:8.8.8.8 https://google.com
curl -w "%{time_total}\n" -o /dev/null -s https://host
# Measure total time
wget -q --spider http://host
# Check availability
hping3 advanced 📄 docs Advanced ping with full control over TCP/UDP/ICMP packets
Examples
hping3 -S -p 80 192.168.1.1
# TCP SYN on port 80
hping3 -1 192.168.1.1
# ICMP ping
hping3 -2 -p 53 8.8.8.8
# UDP to port 53
hping3 --traceroute -S -p 80 host
# TCP traceroute
fping 📄 docs Ping multiple hosts in parallel, ideal for full network sweeps
Examples
fping -a -g 192.168.1.0/24
# Live hosts on the network
fping -c 3 host1 host2 host3
# Multi-host ping with 3 cycles
fping -f hosts.txt
# Read hosts from file

DNS resolution

dig recommended 📄 docs Detailed DNS query with timing, TTL and server used
Examples
dig google.com
# A record (IPv4)
dig AAAA google.com
# IPv6 record
dig MX google.com
# Mail records
dig @8.8.8.8 google.com
# Query specific server
dig -x 8.8.8.8
# Reverse DNS (PTR)
dig +short google.com
# Just the IP
dig +trace google.com
# Full trace from root servers
nslookup 📄 docs Interactive or direct DNS query
Examples
nslookup google.com
nslookup google.com 8.8.8.8
nslookup -type=MX google.com
resolvectl 📄 docs DNS management with systemd-resolved (modern Ubuntu/Debian)
Examples
resolvectl status
# View DNS per interface
resolvectl query google.com
resolvectl statistics
# Cache hits/misses
resolvectl flush-caches
# Flush DNS cache
cat /etc/resolv.conf 📄 docs View DNS servers configured on the system
Also useful
cat /etc/hosts
# Static local resolution
cat /etc/nsswitch.conf
# Resolution order
host 📄 docs Simple and fast DNS resolution, good for scripts
Examples
host google.com
host -t MX google.com
# Specific record type
host 8.8.8.8
# Reverse lookup
host google.com 1.1.1.1
# Use Cloudflare server
whois 📄 docs Domain and IP registration info (ARIN, RIPE, etc.)
Examples
whois google.com
# Domain info
whois 8.8.8.8
# Who owns the IP
whois 192.168.0.0/16
# IP block info

Ports & connections

ss recommended 📄 docs Active sockets: TCP, UDP, UNIX. Replaces netstat
Examples
ss -tulnp
# TCP+UDP LISTEN, no DNS, with PID
ss -tnp state established
# Established connections
ss -s
# Summary statistics
ss -tnp dst 8.8.8.8
# Filter by destination
ss -lnp sport = :80
# What listens on port 80
netstat deprecated 📄 docs View connections and ports (classic, net-tools package)
Examples
netstat -tulnp
# Equivalent to ss -tulnp
netstat -an | grep LISTEN
netstat -s
# Per-protocol statistics
nc (netcat) 📄 docs Test TCP/UDP connectivity to a specific port
Examples
nc -zv 192.168.1.1 22
# Check if port 22 is open
nc -zv host 80 443 8080
# Multiple ports
nc -l 9999
# Simple TCP server
nc -u host 53
# UDP connection
nmap advanced 📄 docs Port and service scanning on remote hosts
Examples
nmap 192.168.1.1
# Common ports
nmap -p 1-65535 192.168.1.1
# All ports
nmap -sV -sC 192.168.1.1
# Service detection
nmap -sn 192.168.1.0/24
# Live hosts on network
lsof -i 📄 docs See which processes have network files open
Examples
lsof -i
# All open network files
lsof -i :80
# What uses port 80
lsof -i TCP:22
# TCP connections to port 22
lsof -i -n -P | grep LISTEN
# Listening ports only
lsof -p 1234 -i
# Network files open by PID 1234
openssl s_client 📄 docs Verify TLS/SSL certificates and HTTPS connections
Examples
openssl s_client -connect google.com:443
openssl s_client -connect host:443 | openssl x509 -noout -dates
# Certificate expiry date
echo | openssl s_client -connect host:443 2>/dev/null | openssl x509 -noout -subject

Routing table

ip route 📄 docs View and manage the routing table
Examples
ip route show
# Full table
ip route get 8.8.8.8
# Which route the kernel uses
ip route add 10.0.0.0/8 via 192.168.1.1
ip route del default
ip route add default via 192.168.1.1 dev eth0
ip neigh 📄 docs ARP table: view neighbors and their MACs
Examples
ip neigh show
# Full ARP table
ip neigh flush all
# Flush ARP cache
arp -n
# Classic alternative
arping 📄 docs Detect IP conflicts or test L2 connectivity
Examples
arping -I eth0 192.168.1.1
# ARP ping to gateway
arping -D -I eth0 192.168.1.50
# Detect duplicate IP

Traffic capture & analysis

tcpdump advanced 📄 docs Capture and filter packets in real time from the terminal
Examples
tcpdump -i eth0
# Capture on eth0 interface
tcpdump -i any port 80
# All HTTP traffic
tcpdump -i eth0 host 192.168.1.1
tcpdump -i eth0 -w captura.pcap
# Save for Wireshark
tcpdump -r captura.pcap
# Read .pcap file
iftop / nethogs 📄 docs Monitor bandwidth by interface or by process
Examples
iftop -i eth0
# BW per connection (interactive)
nethogs eth0
# BW per process
vnstat -l
# Historical statistics
ip -s link 📄 docs TX/RX packet stats, errors and drops per interface
Examples
ip -s link show eth0
# Packet counters
cat /proc/net/dev
# Raw kernel stats
watch -n 1 'ip -s link show eth0'
ngrep advanced 📄 docs Grep over network traffic — search patterns in packet payloads
Examples
ngrep -d eth0 'GET' tcp port 80
# HTTP GET requests
ngrep -d any 'password' port 21
# Search within FTP traffic
ngrep -W byline port 80
# Human-readable line-by-line format
ss -i (info TCP interna) 📄 docs View internal TCP metrics: RTT, cwnd, retransmissions per socket
Examples
ss -tin
# Internal TCP info (RTT, cwnd, retrans)
ss -tin dst 8.8.8.8
# Only towards specific destination
ss -tin state established | grep retrans

Firewall & filtering

iptables 📄 docs View and manage kernel firewall rules
Examples
iptables -L -n -v
# View all rules
iptables -L INPUT -n -v --line-numbers
iptables -t nat -L -n -v
# NAT table
iptables -F
# WARNING: flushes all rules
nft (nftables) modern 📄 docs Replaces iptables on modern systems (kernel 3.13+)
Examples
nft list ruleset
# View all rules
nft list tables
nft list chain inet filter input
ufw 📄 docs Simplified frontend for iptables (Ubuntu/Debian)
Examples
ufw status verbose
ufw allow 22/tcp
ufw deny 80
ufw disable
# Disable for diagnostics
firewall-cmd 📄 docs Firewalld CLI (RHEL/CentOS/Fedora)
Examples
firewall-cmd --list-all
firewall-cmd --state
firewall-cmd --zone=public --list-ports

System logs

journalctl 📄 docs System logs with systemd (kernel, NetworkManager, etc.)
Examples
journalctl -u NetworkManager -f
# NM logs in real time
journalctl -k | grep -i eth
# Filtered kernel logs
journalctl -u systemd-networkd -n 50
journalctl --since "10 min ago"
dmesg 📄 docs Kernel messages: NIC errors, driver, link events
Examples
dmesg | grep -i eth
# Eventos de la interfaz
dmesg | grep -i error
dmesg -w
# Real time (watch mode)
dmesg -T | tail -20
# With human-readable timestamps
sysctl (kernel params) 📄 docs View and modify kernel network parameters
Examples
sysctl net.ipv4.ip_forward
sysctl -a | grep net.core
sysctl net.ipv4.tcp_congestion_control
sysctl -w net.ipv4.ip_forward=1
# Enable IP forwarding
/var/log/syslog y auth.log 📄 docs Traditional system logs and SSH authentication
Examples
tail -f /var/log/syslog | grep -i network
grep "Failed password" /var/log/auth.log
# Failed SSH login attempts
grep sshd /var/log/auth.log | tail -20
last -a | head -20
# Recent logins with source IP

VPN & tunnels

wg / wg-quick modern 📄 docs WireGuard: modern, fast VPN with state-of-the-art cryptography
Examples
wg show
# Status of all WG interfaces
wg show wg0
# Status of wg0 interface
wg-quick up wg0
# Bring up tunnel from /etc/wireguard/wg0.conf
wg-quick down wg0
wg showconf wg0
# Show active tunnel config
openvpn 📄 docs OpenVPN diagnostics and connection
Examples
openvpn --config client.ovpn
# Connect using profile
systemctl status openvpn@client
# Service status
journalctl -u openvpn@client -f
# Real-time logs
ip tuntap show
# View active tun/tap interfaces
ssh tunneling 📄 docs SSH tunnels: local, remote and dynamic (SOCKS proxy)
Examples
ssh -L 8080:dest:80 user@jump
# Local tunnel
ssh -R 9090:localhost:3000 user@remote
# Remote tunnel
ssh -D 1080 user@host
# Dynamic SOCKS5 proxy
ssh -N -f -L 5432:db:5432 user@bastion
# Background tunnel
ip tunnel / ip gre 📄 docs GRE, IPIP and other kernel-level tunnel management
Examples
ip tunnel show
# View active tunnels
ip tunnel add gre1 mode gre remote 10.0.0.2 local 10.0.0.1
ip link show type gre
# GRE interfaces
ip link show type vxlan
# VXLAN interfaces
ipsec / strongswan 📄 docs IPsec VPN diagnostics (IKEv1/IKEv2)
Examples
ipsec status
# IPsec tunnel status
ipsec statusall
# Detailed SA and policy info
ipsec up conexion
# Bring up IPsec tunnel
ip xfrm state
# View kernel Security Associations
ip xfrm policy
# View kernel IPsec policies

Performance & advanced diagnostics

iperf3 recommended 📄 docs Measure real throughput between two hosts (TCP and UDP)
Examples
iperf3 -s
# Server mode (on the destination host)
iperf3 -c 192.168.1.10
# TCP test to server
iperf3 -c host -u -b 100M
# UDP test at 100 Mbps
iperf3 -c host -P 4 -t 30
# 4 parallel streams, 30 seconds
iperf3 -c host -R
# Reverse test (server → client)
speedtest-cli 📄 docs Internet speed test from the terminal
Examples
speedtest-cli
# Full test (ping, download, upload)
speedtest-cli --simple
# Numeric results only
speedtest-cli --list | head -20
# Nearest servers
speedtest-cli --server 1234
# Use specific server
tc (traffic control) advanced 📄 docs QoS, shaping, and network condition simulation (latency, loss)
Examples
tc qdisc show dev eth0
# View active queue disciplines
tc -s qdisc show dev eth0
# With statistics
tc qdisc add dev eth0 root netem delay 100ms
# Simulate 100ms latency
tc qdisc add dev eth0 root netem loss 5%
# Simulate 5% packet loss
tc qdisc del dev eth0 root
# Delete rules
nstat / netstat -s 📄 docs Kernel counters: retransmissions, global TCP/IP errors
Examples
nstat -z
# All kernel counters
nstat | grep -i retrans
# TCP retransmissions
nstat -d 5
# Delta every 5 seconds
cat /proc/net/snmp
# Raw kernel SNMP counters
perf / bpftrace advanced 📄 docs Kernel profiling and network call tracing with eBPF
Examples
perf stat -e net:* ping -c 1 8.8.8.8
# Network events during ping
bpftrace -e 'kprobe:tcp_retransmit_skb { @[comm] = count(); }'
# Retransmissions per process
bpftrace -e 'tracepoint:net:net_dev_xmit { @bytes = sum(args->len); }'

Wi-Fi diagnostics

iwconfig deprecated 📄 docs Wi-Fi interface state: ESSID, frequency, signal strength
Examples
iwconfig
# Info on all wireless interfaces
iwconfig wlan0
# Only wlan0
watch -n 1 iwconfig wlan0
# Monitor signal in real time
iw recommended 📄 docs Modern Wi-Fi management: scan, BSS info, station statistics
Examples
iw dev
# Wi-Fi interfaces and their modes
iw dev wlan0 scan
# Scan available networks
iw dev wlan0 link
# Info on the AP you are connected to
iw dev wlan0 station dump
# Station statistics (signal, BW)
iw phy
# Wi-Fi chipset capabilities
nmcli wifi 📄 docs Wi-Fi management with NetworkManager: scan, connect, forget networks
Examples
nmcli dev wifi list
# Scan Wi-Fi networks
nmcli dev wifi connect "MyNetwork" password "mypassword"
nmcli connection show --active
nmcli radio wifi off
# Disable Wi-Fi
nmcli connection delete "OldNetwork"
wavemon 📄 docs Interactive Wi-Fi monitor: signal, noise, real-time histogram
Examples
wavemon
# Interactive monitor (install: apt install wavemon)
wavemon -i wlan0
# Specify interface
rfkill 📄 docs View and manage hardware/software blocks for Wi-Fi and Bluetooth
Examples
rfkill list
# Status of all devices RF
rfkill unblock wifi
# Unblock Wi-Fi
rfkill block bluetooth
# Block Bluetooth
rfkill unblock all
🔒 Linux Security & Hardening
Auditing
SSH
Access Control
Integrity
Intrusion
Kernel

System auditing

auditd 📄 docs Kernel audit daemon — log file access, syscalls, user actions
Examples
systemctl status auditd
# Check if audit daemon is running
auditctl -l
# List active audit rules
auditctl -w /etc/passwd -p wa -k passwd_changes
# Watch passwd for writes/attribs
auditctl -a always,exit -F arch=b64 -S execve -k exec_log
# Log all exec() calls
auditctl -D
# Delete all rules (temporary)
ausearch / aureport 📄 docs Query and report on audit logs from auditd
Examples
ausearch -k passwd_changes
# Search by audit key
ausearch -m USER_LOGIN -ts today
# Today's login events
ausearch -ui 1000 -ts recent
# Events by UID, recent
aureport --summary
# High-level audit summary
aureport -au
# Authentication report
aureport --failed
# Failed events only
last / lastb / lastlog 📄 docs Login history, failed logins, and last login per user
Examples
last -a | head -20
# Recent logins with source IP
lastb | head -20
# Failed login attempts (requires root)
lastlog
# Last login for every user account
last reboot | head -5
# Recent reboots
who -a
# Currently logged-in users
lynis recommended 📄 docs Full system security audit — checks hardening, configs, vulnerabilities
Examples
lynis audit system
# Full system audit (install: apt install lynis)
lynis audit system --quick
# Skip pause prompts
lynis show details TEST-ID
# Detail on a specific test
cat /var/log/lynis-report.dat | grep warning
# Extract warnings

SSH hardening & diagnostics

sshd config checks 📄 docs Verify key SSH server hardening settings
Key settings to verify in /etc/ssh/sshd_config
PermitRootLogin no
# Disable direct root login
PasswordAuthentication no
# Force key-based auth only
MaxAuthTries 3
# Limit brute-force attempts
AllowUsers deploy alice
# Whitelist allowed users
Port 2222
# Change default port (minor obscurity)
Protocol 2
# SSHv2 only
Apply and verify
sshd -t
# Test config syntax before reloading
systemctl reload sshd
# Apply changes without dropping sessions
ss -tlnp | grep sshd
# Confirm which port sshd is listening on
ssh-keygen / ssh-copy-id 📄 docs Manage SSH key pairs and authorized keys
Examples
ssh-keygen -t ed25519 -C "user@host"
# Generate modern Ed25519 key pair
ssh-keygen -t rsa -b 4096
# RSA 4096-bit key
ssh-copy-id user@server
# Copy public key to remote authorized_keys
ssh-keygen -lf ~/.ssh/authorized_keys
# List fingerprints of authorized keys
cat /etc/ssh/sshd_config | grep AuthorizedKeysFile
fail2ban 📄 docs Auto-ban IPs after repeated failed login attempts
Examples
systemctl status fail2ban
fail2ban-client status
# List active jails
fail2ban-client status sshd
# SSH jail details + banned IPs
fail2ban-client set sshd unbanip 1.2.3.4
# Unban an IP
fail2ban-client set sshd banip 1.2.3.4
# Manually ban an IP
tail -f /var/log/fail2ban.log
ssh -v (debug) 📄 docs Debug SSH connection issues step by step
Examples
ssh -v user@host
# Verbose: shows each auth step
ssh -vvv user@host
# Maximum verbosity
journalctl -u sshd -f
# Server-side SSH logs in real time
grep "Failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn
# Top attacking IPs

Access control — users, sudo, SELinux/AppArmor

users & groups 📄 docs Inspect user accounts, groups, and privilege escalation paths
Examples
cat /etc/passwd | awk -F: '$3==0'
# Find all UID 0 (root) accounts
awk -F: '($2 == "" )' /etc/shadow
# Accounts with empty passwords
getent group sudo
# Who is in the sudo group
groups username
# Groups a user belongs to
id username
# UID, GID, all group memberships
chage -l username
# Password expiry info
sudo 📄 docs Audit sudo configuration and usage
Examples
sudo -l
# What sudo commands can current user run
sudo -l -U username
# sudo rights for another user
visudo -c
# Syntax check sudoers file
grep -r NOPASSWD /etc/sudoers /etc/sudoers.d/
# Find passwordless sudo grants
journalctl -u sudo | grep -i "incorrect\|NOT in sudoers"
SELinux 📄 docs SELinux status, troubleshooting denials (RHEL/CentOS/Fedora)
Examples
getenforce
# Enforcing / Permissive / Disabled
sestatus
# Full SELinux status and policy
setenforce 0
# Temporarily set Permissive (for testing)
audit2why < /var/log/audit/audit.log
# Explain denials in plain English
audit2allow -a -M mypol && semodule -i mypol.pp
# Create and load policy from denials
ls -Z /var/www/html
# Show SELinux context of files
restorecon -Rv /var/www/html
# Restore default file contexts
AppArmor 📄 docs AppArmor status and profile management (Ubuntu/Debian)
Examples
aa-status
# Profiles loaded and their mode
aa-enforce /etc/apparmor.d/usr.sbin.nginx
# Set profile to enforce mode
aa-complain /etc/apparmor.d/usr.sbin.nginx
# Log only, don't enforce
dmesg | grep apparmor
# AppArmor denials in kernel log
journalctl -f | grep apparmor
# Real-time AppArmor events

File integrity and permissions

find (permission audit) 📄 docs Find dangerous file permissions: SUID, world-writable, no-owner
Examples
find / -perm -4000 -type f 2>/dev/null
# SUID binaries (can run as root)
find / -perm -2000 -type f 2>/dev/null
# SGID binaries
find / -perm -0002 -type f 2>/dev/null
# World-writable files
find / -nouser -o -nogroup 2>/dev/null
# Files with no valid owner
find /tmp /var/tmp -type f -ls
# Suspicious files in temp dirs
AIDE / tripwire recommended 📄 docs File integrity monitoring — detect unauthorized changes to system files
AIDE examples
aide --init
# Initialize baseline database
aide --check
# Compare current state to baseline
aide --update
# Update baseline after approved changes
cat /etc/aide/aide.conf
# Configure what to monitor
chkrootkit / rkhunter 📄 docs Scan for rootkits, backdoors, and suspicious binaries
Examples
chkrootkit
# Quick rootkit scan
rkhunter --check
# Rootkit Hunter full scan
rkhunter --update
# Update rkhunter database
rkhunter --check --skip-keypress --report-warnings-only
# Non-interactive, warnings only
debsums / rpm -V 📄 docs Verify installed package files against their checksums
Examples
debsums -c
# Check all packages, show changed files (Debian)
debsums nginx
# Check specific package
rpm -Va
# Verify all RPM packages (RHEL/CentOS)
rpm -Vf /usr/sbin/sshd
# Verify file against its package

Intrusion detection and network exposure

ss / netstat (security) 📄 docs Audit open ports and unexpected listening services
Examples
ss -tulnp
# All listening ports with process names
ss -tulnp | grep -v '127.0.0.1\|::1'
# Publicly exposed ports only
ss -tnp state established
# Active outbound connections
ss -tnp | grep ESTAB | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn
# Top connected IPs
ps / lsof (suspicious processes) 📄 docs Spot unusual or hidden processes and open file descriptors
Examples
ps auxf
# Full process tree — spot unexpected parents
ls -la /proc/*/exe 2>/dev/null | grep deleted
# Processes running deleted binaries (malware sign)
lsof -i -n -P | grep LISTEN
# All listening sockets with process
ls /proc/ | grep -E '^[0-9]+$' | xargs -I{} readlink /proc/{}/exe 2>/dev/null | sort -u
# All unique binaries currently running
crontab audit 📄 docs Find scheduled tasks that could be persistence mechanisms
Examples
crontab -l
# Current user's crontab
for u in $(cut -f1 -d: /etc/passwd); do crontab -u $u -l 2>/dev/null; done
# All users' crontabs
ls -la /etc/cron.*
# System cron directories
cat /etc/crontab
# System-wide crontab
systemctl list-timers --all
# Systemd timers (modern cron alternative)
opensnoop / execsnoop advanced 📄 docs eBPF-based real-time tracing of file opens and process execution
Examples
opensnoop-bpfcc
# Watch every file open in real time
execsnoop-bpfcc
# Watch every process execution in real time
opensnoop-bpfcc -p 1234
# Filter by PID
bpftrace -e 'tracepoint:syscalls:sys_enter_execve { printf("%s %s\n", comm, str(args->filename)); }'

Kernel security hardening

sysctl (security params) 📄 docs Key kernel parameters that harden the system against attacks
Network hardening
sysctl net.ipv4.conf.all.rp_filter
# Reverse path filtering (anti-spoofing)
sysctl net.ipv4.conf.all.accept_redirects
# Should be 0 (reject ICMP redirects)
sysctl net.ipv4.conf.all.send_redirects
# Should be 0 on non-routers
sysctl net.ipv4.tcp_syncookies
# SYN flood protection (should be 1)
sysctl net.ipv4.conf.all.log_martians
# Log bogus source addresses
Kernel hardening
sysctl kernel.randomize_va_space
# ASLR (should be 2)
sysctl kernel.dmesg_restrict
# Restrict dmesg to root (should be 1)
sysctl kernel.kptr_restrict
# Hide kernel pointers (should be 1 or 2)
sysctl fs.suid_dumpable
# Core dumps for SUID (should be 0)
sysctl kernel.yama.ptrace_scope
# Restrict ptrace (1=restricted)
dmesg (security events) 📄 docs Kernel messages related to security: segfaults, OOM, buffer overflows
Examples
dmesg | grep -i "segfault\|protection\|exploit"
dmesg | grep -i "oom\|killed"
# OOM kills
dmesg | grep -i "apparmor\|selinux"
# MAC framework events
dmesg -T | grep -i "audit"
# Audit events with timestamp
openssl & certificate checks 📄 docs Verify TLS certs, ciphers, and expiry dates
Examples
openssl s_client -connect host:443 2>/dev/null | openssl x509 -noout -dates
# Cert expiry
openssl s_client -connect host:443 2>/dev/null | openssl x509 -noout -subject -issuer
openssl ciphers -v 'HIGH:!aNULL:!MD5'
# List strong ciphers
nmap --script ssl-enum-ciphers -p 443 host
# Audit supported ciphers remotely
📦 Storage & Filesystems
Disk Usage
Block Devices
Filesystems
LVM
RAID
S.M.A.R.T.

Disk usage

df 📄 docs Filesystem disk space usage — mounted filesystems at a glance
Examples
df -h
# Human-readable (GB/MB)
df -hT
# Include filesystem type
df -hi
# Inode usage (important — can fill up independently of space)
df -h /var
# Only the filesystem containing /var
watch -n 5 df -h
# Monitor disk usage every 5 seconds
du 📄 docs Directory disk usage — find what is consuming space
Examples
du -sh /var/*
# Size of each item in /var
du -ah /var/log | sort -rh | head -20
# Top 20 largest files in /var/log
du -sh /* 2>/dev/null | sort -rh | head -10
# Top 10 largest root directories
du -h --max-depth=2 /var
# Limit traversal depth
ncdu recommended 📄 docs Interactive ncurses disk usage browser — navigate and find space hogs
Examples
ncdu /
# Interactive browser from root (install: apt install ncdu)
ncdu -x /
# Stay on one filesystem (skip mounts)
ncdu -o report.json /var
# Export result to JSON
ncdu -f report.json
# Browse saved report offline
findmnt 📄 docs Show all mount points with options, source, and filesystem type
Examples
findmnt
# Tree view of all mounts
findmnt -t ext4,xfs
# Filter by filesystem type
findmnt /dev/sda1
# Where is this device mounted
findmnt --verify
# Verify all mounts in fstab are OK

Block devices and partitions

lsblk 📄 docs Tree view of all block devices: disks, partitions, LVM, RAID
Examples
lsblk
# Block device tree
lsblk -f
# Include filesystem type and UUID
lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINT,UUID
# Custom columns
lsblk -d -o NAME,SIZE,ROTA
# ROTA=1 means spinning disk, 0 = SSD
fdisk / parted / gdisk 📄 docs Partition table management — list, create, and modify partitions
Examples
fdisk -l
# List all disks and partitions
fdisk -l /dev/sda
# Specific disk
parted /dev/sda print
# Print partition table (GPT aware)
parted -l
# All disks
gdisk -l /dev/sda
# GPT partition table details
blkid
# UUIDs and filesystem types of all block devices
mount / umount 📄 docs Mount and unmount filesystems, inspect current mounts
Examples
mount | column -t
# All current mounts, formatted
mount /dev/sdb1 /mnt/data
# Mount partition
mount -o remount,ro /
# Remount root read-only
mount -t tmpfs -o size=512m tmpfs /mnt/ramdisk
# RAM disk
umount -l /mnt/data
# Lazy unmount (when busy)
fuser -mv /mnt/data
# What is using this mount point

Filesystem checks and repair

fsck / e2fsck 📄 docs Check and repair filesystem errors (must be unmounted first)
Examples
fsck /dev/sdb1
# Check filesystem (unmount first!)
fsck -n /dev/sdb1
# Dry run — no changes
e2fsck -f /dev/sdb1
# Force check ext2/3/4
e2fsck -p /dev/sdb1
# Auto-fix non-destructive errors
tune2fs -l /dev/sda1 | grep 'Mount count\|Last checked'
# Check interval info
xfs_repair / xfs_info 📄 docs XFS filesystem check, repair, and metadata info
Examples
xfs_info /dev/sda1
# Filesystem info (block size, inode count)
xfs_repair -n /dev/sda1
# Dry run check
xfs_repair /dev/sda1
# Repair (unmount first)
xfs_admin -l /dev/sda1
# Show filesystem label
tune2fs / resize2fs 📄 docs Tune ext filesystem parameters and resize online
Examples
tune2fs -l /dev/sda1
# Print all ext filesystem parameters
tune2fs -m 1 /dev/sda1
# Set reserved blocks to 1% (default 5%)
resize2fs /dev/sda1
# Grow to fill partition (after partition resize)
resize2fs /dev/sda1 20G
# Shrink to 20G (offline only)

LVM — Logical Volume Manager

pvs / vgs / lvs 📄 docs Quick summary of physical volumes, volume groups, and logical volumes
Examples
pvs
# Physical volumes summary
vgs
# Volume groups summary
lvs
# Logical volumes summary
pvdisplay
# Detailed PV info
vgdisplay
# Detailed VG info
lvdisplay
# Detailed LV info
lvextend / lvreduce 📄 docs Resize logical volumes — extend online, shrink offline
Examples
lvextend -L +10G /dev/vg0/data
# Add 10G to LV
lvextend -l +100%FREE /dev/vg0/data
# Use all free VG space
lvextend -r -L +10G /dev/vg0/data
# Extend LV and resize filesystem in one step
vgextend vg0 /dev/sdb
# Add new disk to volume group
pvcreate /dev/sdb
# Initialize disk as PV first
lvm snapshots 📄 docs Create and restore LVM snapshots for backups or safe changes
Examples
lvcreate -L 5G -s -n snap0 /dev/vg0/data
# Create 5G snapshot
lvs -o +lv_attr
# See snapshot status
mount /dev/vg0/snap0 /mnt/snap -o ro
# Mount snapshot read-only
lvconvert --merge /dev/vg0/snap0
# Rollback: merge snapshot back
lvremove /dev/vg0/snap0
# Delete snapshot

RAID — mdadm software RAID

mdadm --detail 📄 docs Check RAID array status, health, and sync progress
Examples
mdadm --detail /dev/md0
# Full RAID array info
cat /proc/mdstat
# All arrays status and sync progress
mdadm --detail --scan
# All arrays, scannable format
watch -n 1 cat /proc/mdstat
# Monitor rebuild in real time
mdadm (manage) 📄 docs Add, remove, and replace drives in a RAID array
Examples
mdadm --manage /dev/md0 --fail /dev/sdb1
# Mark disk as failed
mdadm --manage /dev/md0 --remove /dev/sdb1
# Remove failed disk
mdadm --manage /dev/md0 --add /dev/sdc1
# Add replacement disk (triggers rebuild)
mdadm --create /dev/md0 --level=1 --raid-devices=2 /dev/sda1 /dev/sdb1
# Create RAID1

S.M.A.R.T. disk health

smartctl recommended 📄 docs Query S.M.A.R.T. data and run disk health tests
Examples
smartctl -i /dev/sda
# Disk identity info
smartctl -H /dev/sda
# Overall health assessment (PASSED / FAILED)
smartctl -a /dev/sda
# Full SMART report
smartctl -t short /dev/sda
# Run short self-test (~2 min)
smartctl -t long /dev/sda
# Run extended test (~hours)
smartctl -l selftest /dev/sda
# View self-test results log
Key SMART attributes to watch
Reallocated_Sector_Ct
# Sectors moved due to errors — any value > 0 is a warning
Pending_Sector_Count
# Sectors waiting to be reallocated
Uncorrectable_Sector_Count
# Unrecoverable read errors — replace disk if > 0
Power_On_Hours
# Total disk runtime
Temperature_Celsius
# Disk temperature — >55°C is concerning
smartd 📄 docs Background daemon that monitors SMART and emails on failures
Examples
systemctl status smartd
cat /etc/smartd.conf
# Configure which disks and what to alert on
smartd -q onecheck
# Run one check and exit
journalctl -u smartd
# SMART daemon logs
🔄 Services & Systemd
Services
Journal
Boot Analysis
Timers
Units & Deps
Targets & cgroups

Service management

systemctl (basics) 📄 docs Start, stop, enable, and inspect services
Examples
systemctl status nginx
# Status, recent logs, PID, memory
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl reload nginx
# Reload config without restart (if supported)
systemctl enable nginx
# Start on boot
systemctl disable nginx
systemctl enable --now nginx
# Enable and start immediately
systemctl mask nginx
# Prevent service from ever being started
systemctl (listing) 📄 docs List and filter services by state, type, or failure
Examples
systemctl list-units --type=service
# All loaded services
systemctl list-units --type=service --state=failed
# Failed services
systemctl list-units --type=service --state=running
systemctl --failed
# Shorthand for failed units
systemctl list-unit-files --type=service
# All installed service files + enabled state
systemctl is-active nginx
# Scriptable: returns active/inactive
systemctl is-enabled nginx
# Scriptable: returns enabled/disabled
systemctl edit 📄 docs Override unit file settings without modifying originals
Examples
systemctl edit nginx
# Create drop-in override (survives package updates)
systemctl edit --full nginx
# Edit full unit file copy
systemctl cat nginx
# Show effective unit file with all overrides
systemctl daemon-reload
# Required after editing unit files
ls /etc/systemd/system/nginx.service.d/
# Drop-in directory

journalctl — log querying

journalctl (filtering) 📄 docs Query logs by unit, time, priority, and more
Examples
journalctl -u nginx -f
# Follow nginx logs
journalctl -u nginx --since "1 hour ago"
journalctl -u nginx --since "2024-01-01" --until "2024-01-02"
journalctl -p err
# Only errors and above
journalctl -p warning -u sshd
# Warnings from sshd
journalctl _PID=1234
# Logs from specific PID
journalctl _UID=1000
# Logs from specific UID
journalctl -k
# Kernel messages only (like dmesg)
journalctl -b
# Current boot only
journalctl -b -1
# Previous boot
journalctl (output & maintenance) 📄 docs Format output, manage journal disk usage
Examples
journalctl -u nginx -o json-pretty
# JSON output for parsing
journalctl -u nginx -n 50 --no-pager
# Last 50 lines, no pager
journalctl --disk-usage
# How much space journals are using
journalctl --vacuum-size=500M
# Trim journals to 500MB
journalctl --vacuum-time=30d
# Delete journals older than 30 days
journalctl --list-boots
# All recorded boots with timestamps

Boot time analysis

systemd-analyze recommended 📄 docs Profile boot time — find slow services and bottlenecks
Examples
systemd-analyze
# Total boot time: firmware + loader + kernel + userspace
systemd-analyze blame
# Services sorted by startup time
systemd-analyze critical-chain
# Critical path of boot sequence
systemd-analyze critical-chain nginx.service
# Critical path for specific service
systemd-analyze plot > boot.svg
# Generate SVG timeline chart
systemd-analyze dot | dot -Tsvg > deps.svg
# Dependency graph (requires graphviz)
bootctl / efibootmgr 📄 docs Inspect and manage the bootloader and EFI boot entries
Examples
bootctl status
# Current bootloader and boot entry info
bootctl list
# All boot entries
efibootmgr -v
# EFI boot entries with details
efibootmgr -o 0001,0002
# Set boot order

Systemd timers (modern cron)

systemctl list-timers 📄 docs List all active timers with next/last trigger times
Examples
systemctl list-timers
# Active timers with next run time
systemctl list-timers --all
# Include inactive timers
systemctl status logrotate.timer
systemctl start backup.timer
# Start a timer immediately
journalctl -u backup.service
# Logs from the timer's service
Timer unit example 📄 docs Creating a timer + service pair to replace a cron job
/etc/systemd/system/backup.service
[Unit]
Description=Daily backup
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
/etc/systemd/system/backup.timer
[Unit]
Description=Run backup daily
[Timer]
OnCalendar=daily
Persistent=true
# Run if missed while off
[Install]
WantedBy=timers.target

Units, dependencies, and sockets

systemctl (dependencies) 📄 docs Inspect service dependency trees and ordering
Examples
systemctl list-dependencies nginx
# What nginx depends on
systemctl list-dependencies --reverse nginx
# What depends on nginx
systemctl list-dependencies --all nginx
# Full dependency tree
systemctl show nginx -p Requires,Wants,After
# Specific dependency properties
socket activation 📄 docs Systemd socket units — start services on demand when connection arrives
Examples
systemctl list-units --type=socket
# All active socket units
systemctl status sshd.socket
systemctl cat sshd.socket
# View socket unit definition
systemctl show nginx.socket -p ListenStream
# What port/path it listens on
systemd-run 📄 docs Run a command as a transient systemd unit — with resource limits
Examples
systemd-run --unit=mytask ./script.sh
# Run as transient service
systemd-run --on-calendar="*-*-* 03:00" /usr/bin/backup.sh
# One-off scheduled run
systemd-run -p MemoryMax=512M -p CPUQuota=25% ./app
# Run with resource limits
systemd-run --scope -p MemoryMax=1G ./heavy_process
# Scope (group existing PID)

Targets and cgroup resource management

systemctl (targets) 📄 docs Manage runlevels — systemd targets replace SysV init levels
Examples
systemctl get-default
# Default target (graphical / multi-user)
systemctl set-default multi-user.target
# Boot to CLI (no GUI)
systemctl isolate rescue.target
# Switch to rescue mode now
systemctl list-units --type=target
# All active targets
systemctl poweroff
systemctl reboot
systemctl suspend
systemd-cgtop 📄 docs Real-time cgroup resource usage — CPU, memory, I/O per service
Examples
systemd-cgtop
# Interactive real-time cgroup monitor
systemd-cgtop -d 2
# Refresh every 2 seconds
systemd-cgtop -m
# Sort by memory
systemd-cgtop -n 1 -b
# One-shot batch output
systemctl set-property nginx.service MemoryMax=512M
# Limit memory at runtime
systemctl set-property nginx.service CPUQuota=50%
⚙️ Kernel & Hardware
Hardware Info
Kernel Modules
Device Management
Boot & Firmware

Hardware discovery and inspection

lspci 📄 docs List all PCI devices: GPUs, NICs, storage controllers
Examples
lspci
# All PCI devices summary
lspci -v
# Verbose: driver, IRQ, memory regions
lspci -k
# Show kernel driver in use for each device
lspci -nn
# Include vendor/device IDs (useful for lookups)
lspci | grep -i 'vga\|3d\|display'
# Find GPU(s)
lspci | grep -i net
# Network controllers only
lsusb 📄 docs List USB buses and connected devices with vendor/product IDs
Examples
lsusb
# All USB devices
lsusb -v
# Verbose device info (requires root)
lsusb -t
# Tree view: bus topology and speed
lsusb -d 046d:c52b
# Filter by vendor:product ID
watch -n 2 lsusb
# Monitor USB device plug/unplug
lshw recommended 📄 docs Detailed hardware configuration: CPU, memory, disks, NICs
Examples
lshw
# Full hardware report (requires root)
lshw -short
# Compact one-line-per-device view
lshw -class memory
# RAM slots, size, speed
lshw -class disk -class storage
# Disk and storage controllers
lshw -html > hardware.html
# Export to HTML report
lshw -json
# JSON output for automation
dmidecode 📄 docs Read BIOS/UEFI DMI table: serial numbers, memory slots, chassis info
Examples
dmidecode -t system
# Vendor, model, serial number
dmidecode -t memory
# RAM slots, size, speed, manufacturer
dmidecode -t bios
# BIOS version and release date
dmidecode -t processor
# CPU socket, cores, max speed
dmidecode -s system-serial-number
# Just the serial number (good for scripts)
uname / hostnamectl 📄 docs Kernel version, architecture, and OS identity
Examples
uname -r
# Running kernel version
uname -a
# All: kernel, hostname, arch, build date
hostnamectl
# OS, kernel, virtualization, hardware (systemd)
cat /etc/os-release
# Distro name, version, ID
arch
# CPU architecture (x86_64, aarch64, etc.)
sensors / lm-sensors 📄 docs Read CPU, GPU, and motherboard temperature and fan speed sensors
Examples
sensors
# All sensor readings (install: apt install lm-sensors)
sensors-detect
# Auto-detect sensor chips (run once after install)
sensors -u
# Raw values in machine-readable format
watch -n 2 sensors
# Monitor temperatures in real time
cat /sys/class/thermal/thermal_zone*/temp
# Raw kernel thermal zone values (÷1000 = °C)

Kernel modules

lsmod 📄 docs List currently loaded kernel modules and their use count
Examples
lsmod
# All loaded modules: name, size, use count
lsmod | grep nvidia
# Check if a specific module is loaded
cat /proc/modules
# Raw kernel module list
modprobe 📄 docs Load and unload kernel modules with automatic dependency resolution
Examples
modprobe br_netfilter
# Load a module (with all deps)
modprobe -r br_netfilter
# Unload a module
modprobe -n -v br_netfilter
# Dry run — show what would be loaded
echo "br_netfilter" >> /etc/modules-load.d/k8s.conf
# Persist load across reboots
echo "options usb_storage quirks=0781:5406:u" >> /etc/modprobe.d/usb.conf
# Persist module options
modinfo 📄 docs Module metadata: version, author, available parameters, dependencies
Examples
modinfo ext4
# Full module info
modinfo -F version ext4
# Only the version field
modinfo -F parm e1000e
# Available parameters for a module
modinfo -F depends vboxdrv
# Module dependency list
dkms recommended 📄 docs Dynamic Kernel Module Support — rebuild out-of-tree modules on kernel upgrade
Examples
dkms status
# List all DKMS modules and build status
dkms install -m nvidia -v 535.154.05
# Build and install a DKMS module
dkms remove -m vboxhost -v 7.0.12 --all
# Remove module for all kernels
dkms build -m wireguard -v 1.0.0
# Build without installing
dkms autoinstall
# Rebuild all DKMS modules for current kernel
depmod / update-initramfs 📄 docs Rebuild module dependency map and regenerate initramfs
Examples
depmod -a
# Regenerate module dependency files
update-initramfs -u
# Update initramfs for current kernel (Debian/Ubuntu)
update-initramfs -u -k all
# Update for all installed kernels
dracut --force
# Regenerate initrd (RHEL/Fedora)
mkinitcpio -P
# Rebuild all initramfs presets (Arch)

udev — device event management

udevadm 📄 docs Query udev database, monitor events, test and reload rules
Examples
udevadm monitor
# Watch device events in real time (plug/unplug)
udevadm info -a -n /dev/sda
# All attributes for a device (use to write rules)
udevadm info -q all -n /dev/sda
# Device properties
udevadm test /sys/block/sda
# Simulate rule processing for a device
udevadm control --reload-rules && udevadm trigger
# Reload rules and re-trigger events
udev rules 📄 docs Write persistent device naming, permissions, and action rules
Rule files location
/etc/udev/rules.d/
# Custom rules (lower number = higher priority)
/lib/udev/rules.d/
# System rules (do not edit)
Example rules
SUBSYSTEM=="usb", ATTR{idVendor}=="046d", MODE="0666"
# Set permissions for Logitech USB devices
KERNEL=="sd*", ATTRS{serial}=="ABC123", SYMLINK+="mydisk"
# Persistent /dev/mydisk symlink by serial
ACTION=="add", SUBSYSTEM=="net", ATTR{address}=="aa:bb:cc:dd:ee:ff", NAME="eth-mgmt"
# Rename NIC by MAC address
sysfs (/sys) 📄 docs Virtual filesystem exposing kernel objects, device attributes, and tunables
Examples
ls /sys/block/
# All block devices
cat /sys/block/sda/size
# Disk size in 512-byte sectors
cat /sys/class/net/eth0/speed
# NIC link speed in Mbps
cat /sys/class/power_supply/BAT0/capacity
# Battery percentage
cat /sys/class/thermal/thermal_zone0/temp
# CPU temp in millidegrees

Boot, UEFI & firmware

fwupdmgr recommended 📄 docs Update device firmware (BIOS, NVMe, Thunderbolt) from Linux via LVFS
Examples
fwupdmgr get-devices
# List devices with firmware support
fwupdmgr refresh
# Refresh firmware update metadata
fwupdmgr get-updates
# Check for available updates
fwupdmgr update
# Apply all available firmware updates
fwupdmgr get-history
# Show firmware update history
efibootmgr 📄 docs Manage UEFI boot entries and boot order
Examples
efibootmgr -v
# List all boot entries with details
efibootmgr -o 0001,0002,0003
# Set boot order
efibootmgr -n 0001
# Boot this entry once on next reboot only
efibootmgr -b 0001 -A
# Disable a boot entry
efibootmgr -b 0001 -B
# Delete a boot entry permanently
ipmitool advanced 📄 docs IPMI/BMC interface — remote power control, sensors, SEL on servers
Examples
ipmitool sdr list
# All sensor readings from BMC
ipmitool sel list
# System Event Log
ipmitool chassis status
# Power state and chassis info
ipmitool -H 10.0.0.5 -U admin -P pass chassis power cycle
# Remote power cycle
ipmitool lan print 1
# BMC network configuration
💾 Backup & Recovery
File Sync
Archives
Snapshots
Disk Imaging

File synchronization

rsync recommended 📄 docs Fast incremental file transfer — local or remote, delta-only sync
Examples
rsync -avh /src/ /dst/
# Archive mode, verbose, human-readable
rsync -avh --delete /src/ /dst/
# Mirror: delete files not in src
rsync -avzh /src/ user@host:/dst/
# Remote sync with compression
rsync -avhn /src/ /dst/
# Dry run — show what would change
rsync -avh --exclude='*.log' --exclude='.git' /src/ /dst/
# Exclude patterns
rsync -avh --bwlimit=10000 /src/ user@host:/dst/
# Limit bandwidth to 10 MB/s
rsync -e "ssh -p 2222" -avh /src/ user@host:/dst/
# Custom SSH port
Key flags
-a
# Archive: recursive + preserve perms, times, symlinks, owner
-z
# Compress during transfer (good for slow links)
--progress
# Show per-file transfer progress
--checksum
# Compare by checksum, not mtime (slower but accurate)
scp / sftp 📄 docs Secure copy over SSH — simpler than rsync for one-off transfers
Examples
scp file.txt user@host:/remote/path/
# Upload a file
scp user@host:/remote/file.txt ./
# Download a file
scp -r /local/dir user@host:/remote/
# Recursive directory copy
scp -P 2222 file.txt user@host:/path/
# Custom SSH port
sftp user@host
# Interactive SFTP session (get, put, ls)

Archiving and compression

tar recommended 📄 docs Create and extract archives — the standard Linux backup format
Create archives
tar -czvf archive.tar.gz /path/to/dir
# Create gzip-compressed archive
tar -cjvf archive.tar.bz2 /path/
# bzip2 compression (slower, better ratio)
tar -cJvf archive.tar.xz /path/
# xz compression (best ratio)
tar -cvf archive.tar /path/ --exclude='*.log'
# No compression, with exclusions
tar -czvf - /path/ | ssh user@host "cat > /backup/archive.tar.gz"
# Stream directly over SSH
Extract archives
tar -xzvf archive.tar.gz
# Extract to current directory
tar -xzvf archive.tar.gz -C /target/dir
# Extract to specific directory
tar -tzvf archive.tar.gz
# List contents without extracting
tar -xzvf archive.tar.gz path/to/single/file
# Extract a single file
gzip / bzip2 / xz / zstd 📄 docs Standalone compression tools — trade speed vs ratio
Examples
gzip -k file.log
# Compress, keep original (-k)
gunzip file.log.gz
# Decompress
zstd -T0 -19 bigfile
# zstd max compression, all CPU threads
zstd -d file.zst
# Decompress zstd
xz -9 -T0 file
# xz max compression, multithreaded
xz -d file.xz
# Decompress xz
Speed vs ratio cheat sheet
gzip
# Fast, decent ratio — best for logs and scripts
zstd
# Fast + good ratio — best modern choice
bzip2
# Slow, good ratio — largely superseded
xz
# Slowest, best ratio — best for distribution packages
zip / unzip 📄 docs Cross-platform archives — useful when sharing with Windows/macOS users
Examples
zip -r archive.zip /path/to/dir
# Recursive zip
zip -r archive.zip /path/ -x "*.git*"
# Exclude patterns
unzip archive.zip
# Extract to current directory
unzip archive.zip -d /target/
# Extract to specific directory
unzip -l archive.zip
# List contents without extracting

Deduplicated snapshot backups

restic recommended 📄 docs Fast, encrypted, deduplicated backups to local or cloud storage
Examples
restic init --repo /mnt/backup
# Initialize a new repository
restic -r /mnt/backup backup /home/user
# Create a snapshot
restic -r /mnt/backup snapshots
# List all snapshots
restic -r /mnt/backup restore latest --target /tmp/restore
# Restore latest snapshot
restic -r /mnt/backup forget --keep-daily 7 --keep-weekly 4 --prune
# Apply retention policy
restic -r /mnt/backup check
# Verify repository integrity
restic -r s3:s3.amazonaws.com/bucket backup /data
# Backup directly to S3
borgbackup recommended 📄 docs Deduplicating, compressed, encrypted backup with pruning and FUSE mount
Examples
borg init --encryption=repokey /mnt/backup/repo
# Initialize with encryption
borg create /mnt/backup/repo::backup-{now:%Y-%m-%d} /home /etc
# Create named snapshot
borg list /mnt/backup/repo
# List all archives
borg extract /mnt/backup/repo::backup-2024-01-01 home/user/docs
# Extract specific path
borg mount /mnt/backup/repo /mnt/restore
# Mount as FUSE filesystem for browsing
borg prune -v --keep-daily=7 --keep-weekly=4 /mnt/backup/repo
# Apply retention policy
borg check /mnt/backup/repo
# Verify repository consistency
duplicity 📄 docs Encrypted incremental backups to S3, SFTP, FTP, and more
Examples
duplicity /home/user s3://my-bucket/backup
# Backup to S3
duplicity --full-if-older-than 30D /home/user s3://my-bucket/backup
# Full backup if last full > 30 days
duplicity list-current-files s3://my-bucket/backup
# List backed-up files
duplicity restore s3://my-bucket/backup /tmp/restore
# Restore latest
duplicity remove-older-than 60D s3://my-bucket/backup
# Remove old backups

Disk and partition imaging

dd (disk imaging) 📄 docs Low-level block-for-block disk and partition cloning
Examples
dd if=/dev/sda of=/mnt/backup/sda.img bs=4M status=progress
# Full disk image
dd if=/dev/sda1 of=/mnt/backup/sda1.img bs=4M status=progress
# Single partition image
dd if=/mnt/backup/sda.img of=/dev/sdb bs=4M status=progress
# Restore image to disk
dd if=/dev/sda bs=512 count=1 of=mbr.bin
# Backup MBR only (first 512 bytes)
dd if=/dev/urandom of=/dev/sda bs=4M status=progress
# Securely wipe disk
Pipe with compression
dd if=/dev/sda bs=4M | gzip -c > sda.img.gz
# Compressed image
gunzip -c sda.img.gz | dd of=/dev/sda bs=4M status=progress
# Restore compressed image
dd if=/dev/sda bs=4M | zstd -T0 > sda.img.zst
# Faster with zstd
testdisk / photorec advanced 📄 docs Recover lost partitions and deleted files from damaged disks
Examples
testdisk /dev/sda
# Interactive partition recovery — Analyse → Quick Search
photorec /dev/sda
# Recover deleted files by file signature
testdisk disk_image.img
# Operate on a disk image instead of live device
partclone 📄 docs Filesystem-aware partition cloning — only copies used blocks, much faster than dd
Examples
partclone.ext4 -c -s /dev/sda1 -o sda1.img
# Clone ext4 partition
partclone.ext4 -r -s sda1.img -o /dev/sda1
# Restore ext4 image
partclone.ext4 -c -s /dev/sda1 | gzip > sda1.img.gz
# Clone with compression
partclone.ntfs -c -s /dev/sda1 -o sda1.img
# NTFS partition
🐳 Containers & Virtualization
Docker / Podman
Kubernetes
KVM / QEMU
Build & Provision
LXC / LXD

Docker & Podman — container management

docker (basics) recommended 📄 docs Run, inspect, and manage containers and images
Containers
docker ps
# Running containers
docker ps -a
# All containers including stopped
docker run -d -p 8080:80 --name web nginx
# Run detached with port mapping
docker run -it --rm ubuntu bash
# Interactive, auto-remove on exit
docker exec -it web bash
# Shell into running container
docker stop web && docker rm web
# Stop and remove
docker logs -f web
# Follow container logs
docker inspect web
# Full container metadata (JSON)
docker stats
# Live CPU/memory usage per container
Images
docker images
# List local images
docker pull nginx:alpine
# Pull an image
docker build -t myapp:1.0 .
# Build from Dockerfile in current dir
docker tag myapp:1.0 registry/myapp:1.0
# Tag for pushing
docker push registry/myapp:1.0
# Push to registry
docker image prune -a
# Remove all unused images
docker compose recommended 📄 docs Define and run multi-container applications with a YAML file
Examples
docker compose up -d
# Start all services in background
docker compose down
# Stop and remove containers and networks
docker compose down -v
# Also remove named volumes
docker compose ps
# Status of all services
docker compose logs -f app
# Follow logs of a specific service
docker compose exec app bash
# Shell into a running service
docker compose build --no-cache
# Rebuild images
docker compose pull
# Pull latest images for all services
podman recommended 📄 docs Rootless, daemonless drop-in replacement for Docker — same CLI syntax
Examples
podman run -d -p 8080:80 nginx
# Run as non-root (rootless by default)
podman ps -a
# All containers (same as docker ps -a)
podman generate systemd --name web > web.service
# Generate systemd unit for a container
podman pod create --name mypod -p 8080:80
# Create a pod (group of containers)
podman machine init && podman machine start
# Start VM for rootless mode (macOS/Win)
podman play kube pod.yaml
# Run Kubernetes YAML with Podman
docker system / docker volume 📄 docs System-wide cleanup, disk usage, and volume management
Examples
docker system df
# Disk usage: images, containers, volumes, cache
docker system prune -af --volumes
# Remove ALL unused resources (careful!)
docker volume ls
# List all volumes
docker volume inspect myvolume
# Volume details and mountpoint
docker volume rm myvolume
# Remove a volume
docker network ls
# List all networks
docker network inspect bridge
# Inspect network (containers, IPs)

Kubernetes — kubectl basics

kubectl (cluster & context) 📄 docs Manage cluster contexts and check cluster health
Examples
kubectl config get-contexts
# List all kubeconfig contexts
kubectl config use-context prod
# Switch to a context
kubectl config current-context
# Show active context
kubectl cluster-info
# API server and DNS endpoints
kubectl get nodes -o wide
# All nodes with IPs and roles
kubectl top nodes
# CPU/memory usage per node
kubectl (workloads) 📄 docs Inspect and manage pods, deployments, services, and namespaces
Pods & Deployments
kubectl get pods -n default -o wide
# All pods in namespace with node info
kubectl get pods -A
# All pods across all namespaces
kubectl describe pod mypod -n default
# Full pod info, events, conditions
kubectl logs mypod -f --tail=100
# Follow pod logs
kubectl exec -it mypod -- bash
# Shell into a pod
kubectl rollout status deployment/myapp
# Watch rollout progress
kubectl rollout undo deployment/myapp
# Rollback to previous version
kubectl scale deployment/myapp --replicas=3
# Scale replicas
kubectl delete pod mypod --grace-period=0
# Force delete stuck pod
Resources & apply
kubectl apply -f manifest.yaml
# Create or update from file
kubectl delete -f manifest.yaml
# Delete resources from file
kubectl get all -n mynamespace
# All resources in namespace
kubectl top pods -n default
# CPU/memory per pod
kubectl get events --sort-by='.lastTimestamp' -A
# Recent events cluster-wide
helm recommended 📄 docs Kubernetes package manager — install, upgrade, and manage chart releases
Examples
helm repo add bitnami https://charts.bitnami.com/bitnami
# Add a chart repository
helm repo update
# Update all repo indexes
helm search repo nginx
# Search available charts
helm install myrelease bitnami/nginx -n mynamespace
# Install a chart
helm upgrade myrelease bitnami/nginx --set replicas=3
# Upgrade with value override
helm list -A
# All releases across namespaces
helm rollback myrelease 1
# Rollback to revision 1
helm uninstall myrelease -n mynamespace
# Uninstall a release
k9s recommended 📄 docs Terminal UI for Kubernetes — browse and manage cluster resources interactively
Examples
k9s
# Launch TUI (uses current kubeconfig context)
k9s -n mynamespace
# Start in a specific namespace
k9s --context prod
# Use a specific context
Key shortcuts inside k9s
:
# Command mode — type resource name (pods, svc, deploy...)
l
# View logs for selected pod
s
# Shell into selected pod
d
# Describe selected resource
ctrl+d
# Delete selected resource

KVM / QEMU — virtual machines

virsh 📄 docs Manage KVM/QEMU VMs via libvirt — start, stop, snapshot, console
Examples
virsh list --all
# All VMs and their state
virsh start myvm
# Start a VM
virsh shutdown myvm
# Graceful shutdown
virsh destroy myvm
# Force stop (like power cut)
virsh console myvm
# Attach to serial console (Ctrl+] to exit)
virsh dominfo myvm
# VM info: memory, vCPUs, state
virsh snapshot-create-as myvm snap1 "before upgrade"
# Create snapshot
virsh snapshot-revert myvm snap1
# Revert to snapshot
virsh dumpxml myvm > myvm.xml
# Export VM definition
virsh net-list --all
# Virtual networks
virt-install 📄 docs Create new KVM VMs from the command line
Examples
virt-install \ --name ubuntu24 \ --ram 2048 \ --vcpus 2 \ --disk path=/var/lib/libvirt/images/ubuntu24.qcow2,size=20 \ --cdrom /tmp/ubuntu-24.04-server.iso \ --os-variant ubuntu24.04 \ --network bridge=virbr0
# Create VM from ISO
virt-install --name myvm --ram 1024 --vcpus 1 \ --disk /var/lib/libvirt/images/myvm.qcow2,size=10 \ --location http://archive.ubuntu.com/ubuntu/dists/noble/main/installer-amd64/ \ --extra-args "console=ttyS0"
# Network install with serial console
qemu-img 📄 docs Create, convert, inspect, and resize QEMU disk images
Examples
qemu-img create -f qcow2 disk.qcow2 20G
# Create a new qcow2 image
qemu-img info disk.qcow2
# Image format, virtual size, disk usage
qemu-img convert -f raw -O qcow2 disk.raw disk.qcow2
# Convert raw to qcow2
qemu-img convert -f qcow2 -O vmdk disk.qcow2 disk.vmdk
# Convert to VMware format
qemu-img resize disk.qcow2 +10G
# Grow disk image by 10G
qemu-img snapshot -l disk.qcow2
# List internal snapshots
virt-customize / virt-sysprep advanced 📄 docs Modify disk images offline — inject files, run commands, reset passwords
Examples
virt-customize -a disk.qcow2 --root-password password:newpass
# Reset root password
virt-customize -a disk.qcow2 --copy-in /etc/hosts:/etc/
# Inject a file into the image
virt-customize -a disk.qcow2 --run-command 'apt-get install -y nginx'
# Run command inside image
virt-sysprep -a disk.qcow2
# Seal image for cloning (reset SSH keys, machine-id)

Build & provision — Packer, Vagrant, Buildah, Skopeo

packer recommended 📄 docs Build identical machine images for multiple platforms from a single config
Examples
packer init .
# Download required plugins from packer config
packer validate template.pkr.hcl
# Validate config syntax
packer build template.pkr.hcl
# Build the image
packer build -var 'region=eu-west-1' template.pkr.hcl
# Override variables
packer build -only='amazon-ebs.*' template.pkr.hcl
# Build only AWS AMI
packer build -debug template.pkr.hcl
# Debug mode (pause at each step)
Minimal HCL template (ubuntu + AWS)
source "amazon-ebs" "ubuntu" {
ami_name = "my-ubuntu-{{timestamp}}"
instance_type = "t3.micro"
source_ami_filter { ... }
}
build { sources = ["source.amazon-ebs.ubuntu"] }
vagrant 📄 docs Provision and manage reproducible dev VMs with a single Vagrantfile
Examples
vagrant init ubuntu/noble64
# Create a Vagrantfile for Ubuntu 24.04
vagrant up
# Create and provision the VM
vagrant ssh
# SSH into the running VM
vagrant halt
# Gracefully stop the VM
vagrant destroy -f
# Destroy the VM (irreversible)
vagrant reload --provision
# Restart and re-run provisioners
vagrant snapshot save before-upgrade
# Save a snapshot
vagrant status
# VM state
buildah recommended 📄 docs Build OCI/Docker container images without a daemon — rootless and scriptable
Examples
buildah build -t myapp:1.0 .
# Build from Dockerfile (rootless)
buildah from ubuntu:24.04
# Start a working container from base image
buildah run mycontainer -- apt-get install -y nginx
# Run command in working container
buildah copy mycontainer ./app /app
# Copy files into container
buildah commit mycontainer myapp:1.0
# Commit to image
buildah push myapp:1.0 docker://registry/myapp:1.0
# Push to registry
skopeo 📄 docs Inspect, copy, and sync container images between registries — no daemon needed
Examples
skopeo inspect docker://nginx:alpine
# Inspect remote image metadata without pulling
skopeo copy docker://nginx:alpine docker://myregistry/nginx:alpine
# Copy between registries
skopeo copy docker://nginx:alpine docker-archive:nginx.tar
# Save to local tar archive
skopeo sync --src docker --dest dir nginx:alpine /tmp/images/
# Sync image to directory
skopeo list-tags docker://nginx
# List all available tags
skopeo delete docker://myregistry/myapp:old
# Delete an image from registry
crane / cosign advanced 📄 docs Container registry interactions and image signing/verification
crane examples
crane digest nginx:alpine
# Get image digest without pulling
crane ls nginx
# List tags in a registry
crane cp nginx:alpine myregistry/nginx:alpine
# Fast registry-to-registry copy
crane config nginx:alpine
# Image config JSON (entrypoint, env, layers)
cosign examples
cosign generate-key-pair
# Generate signing key pair
cosign sign --key cosign.key myregistry/myapp:1.0
# Sign an image
cosign verify --key cosign.pub myregistry/myapp:1.0
# Verify image signature

LXC / LXD — system containers

lxc (LXD CLI) recommended 📄 docs Manage LXD containers and VMs — full OS containers, not app containers
Examples
lxc launch ubuntu:24.04 mycontainer
# Create and start a container
lxc list
# All containers: state, IP, type
lxc exec mycontainer -- bash
# Shell into container
lxc stop mycontainer
# Stop container
lxc delete mycontainer
# Delete container
lxc snapshot mycontainer snap1
# Create snapshot
lxc restore mycontainer snap1
# Restore from snapshot
lxc copy mycontainer newcontainer
# Clone a container
lxc config set mycontainer limits.memory 512MB
# Set memory limit
lxc file push ./app.conf mycontainer/etc/app.conf
# Copy file into container
lxc (profiles & networks) 📄 docs Reusable configuration profiles and network management for LXD
Profiles
lxc profile list
# List all profiles
lxc profile show default
# Show a profile definition
lxc profile create myprofile
# Create a new profile
lxc profile assign mycontainer default,myprofile
# Apply profiles to container
Networks
lxc network list
# All LXD networks
lxc network show lxdbr0
# Network details and config
lxc network create mynet ipv4.address=10.10.10.1/24
# Create a bridge network
systemd-nspawn advanced 📄 docs Lightweight OS container using systemd — no extra tooling required
Examples
systemd-nspawn -D /var/lib/machines/mycontainer
# Start container from directory
systemd-nspawn -D /path -b
# Boot full OS (runs init)
machinectl list
# List running nspawn machines
machinectl shell mycontainer
# Shell into running machine
machinectl stop mycontainer
# Stop machine