Complete Linux Guide
From ls and cd to kernel modules and container orchestration. This documentation covers everything you need to master Linux — with practical examples, deep explanations, and best practices from official documentation.
1 Introduction to Linux
What is Linux and why should you learn it?
Linux is a Unix-like, open-source operating system kernel first released by Linus Torvalds in 1991. Built on the principles of portability, multi-user support, and security, Linux has grown into the backbone of modern computing infrastructure — powering servers, cloud platforms, supercomputers, embedded systems, and mobile devices (via Android).
Key Features
- Open Source: Full source code available under the GPL license — free to use, modify, and distribute
- Multi-user & Multi-tasking: Multiple users and processes run simultaneously without interference
- Security: Robust permission system, SELinux/AppArmor, and regular security patches
- Stability: Uptimes measured in years; the kernel rarely crashes
- Portability: Runs on x86, ARM, RISC-V, and virtually every hardware architecture
- Modular Design: Loadable kernel modules (LKMs) extend functionality without rebooting
Main Applications
| Domain | Key Technologies | Example |
|---|---|---|
| Web Servers | Nginx, Apache, Caddy | Google, Facebook, Netflix |
| Cloud & DevOps | Docker, Kubernetes, Ansible | AWS, Azure, GCP infrastructure |
| Supercomputing | MPI, OpenMP, SLURM | Top 500 supercomputers (100% run Linux) |
| Embedded & IoT | Buildroot, Yocto, OpenWrt | Routers, smart TVs, Tesla cars |
| Mobile | Android (Linux kernel) | 3+ billion active devices |
2 Linux Distributions
Choosing the right distro for your needs
A Linux distribution (distro) is an operating system made from the Linux kernel plus a collection of software packages, package manager, and often a desktop environment. Different distros target different use cases — from servers to desktops to embedded systems.
Major Distribution Families
| Family | Package Manager | Popular Distros | Best For |
|---|---|---|---|
| Debian | apt, dpkg | Debian, Ubuntu, Linux Mint, Pop!_OS | Servers, desktops, beginners |
| Red Hat | dnf, rpm | Fedora, RHEL, CentOS Stream, AlmaLinux, Rocky Linux | Enterprise servers, workstations |
| Arch | pacman | Arch Linux, Manjaro, EndeavourOS | Power users, rolling release |
| SUSE | zypper | openSUSE, SUSE Linux Enterprise | Enterprise, YaST administration |
| Gentoo | Portage | Gentoo, ChromeOS | Source-based, maximum control |
| Alpine | apk | Alpine Linux | Containers, minimal footprint |
Release Models
- Fixed Release: Major versions released on a schedule (e.g., Ubuntu 24.04 LTS, RHEL 9). Stable and predictable.
- Rolling Release: Continuous updates (e.g., Arch, openSUSE Tumbleweed). Always up-to-date but requires more maintenance.
- Long-Term Support (LTS): Extended security updates (5+ years). Ideal for production servers.
3 Terminal Basics
Mastering the command line interface
The terminal (or shell) is the primary interface for interacting with Linux. Unlike graphical interfaces, the command line offers precision, automation, and remote administration capabilities that are essential for system administration.
Common Shells
| Shell | Path | Description |
|---|---|---|
bash | /bin/bash | Bourne Again SHell — default on most distros |
zsh | /bin/zsh | Z Shell — powerful scripting, popular with developers |
fish | /usr/bin/fish | Friendly Interactive SHell — auto-suggestions, colors |
sh | /bin/sh | POSIX-compliant shell — portable scripts |
Basic Terminal Commands
Clears everything currently shown in the terminal window and gives you a blank screen.
Shows a numbered list of the commands you've previously run in this shell.
Searches your command history for lines that mention "apt" — handy for finding a command you ran a while ago.
Re-runs command number 42 from your history, exactly as it was typed the first time.
Prints the path of your default login shell (e.g. /bin/bash).
Prints the name of the shell that is actually running right now, which is useful when $SHELL doesn't match reality.
Tab completion also speeds things up: press TAB once to auto-complete commands, files, and directory names, or press it twice in a row to list every possible completion.
Keyboard Shortcuts
Ctrl+CInterrupts (kills) the process currently running in the foreground.Ctrl+DExits the shell by sending an end-of-file (EOF) signal.Ctrl+LClears the screen — the keyboard equivalent of runningclear.Ctrl+AMoves the cursor to the beginning of the current line.Ctrl+EMoves the cursor to the end of the current line.Ctrl+UClears the line from the cursor back to the beginning.Ctrl+KClears the line from the cursor to the end.Ctrl+RStarts a reverse search through your command history.Ctrl+ZSuspends the foreground process, sending it to the background.
Getting Help
Manual pages - the most comprehensive documentation.
Manual for 'ls' command.
Search man pages by keyword.
Section 5: file formats.
Brief description.
Search for commands by description.
Built-in help.
Help for bash built-ins.
Info pages (more detailed than man)
4 File System Hierarchy
Understanding the Linux directory structure
Linux follows the Filesystem Hierarchy Standard (FHS), which defines the directory structure and its contents. Understanding this hierarchy is fundamental to navigation and system administration.
| Directory | Purpose |
|---|---|
/ | Root directory — the top of the filesystem tree |
/bin | Essential user command binaries (ls, cp, mv) |
/sbin | System administration binaries (fdisk, mkfs) |
/etc | System-wide configuration files |
/home | User home directories |
/root | Home directory for root user |
/var | Variable data — logs, caches, spool files |
/tmp | Temporary files (cleared on reboot) |
/usr | User programs, libraries, documentation |
/usr/bin | Non-essential user binaries |
/usr/local | Locally installed software |
/opt | Optional application software packages |
/dev | Device files (disks, terminals, null) |
/proc | Virtual filesystem for process/kernel info |
/sys | Virtual filesystem for system/hardware info |
/mnt | Temporary mount point for filesystems |
/media | Mount point for removable media (USB, CD) |
/boot | Boot loader files (kernel, initramfs) |
/lib | Essential shared libraries |
/srv | Data for services (web, FTP) |
6 File Operations
Creating, copying, moving, and deleting files
Create files.
Create empty file or update timestamp.
Create multiple files.
Create with content (overwrite)
Append to file.
Copy files and directories.
Copy file.
Recursive copy (directories)
Interactive (prompt before overwrite)
Verbose.
Archive mode (preserve permissions, links)
Move and rename.
Rename.
Move to directory.
Interactive.
Delete files and directories.
Remove file.
Interactive.
Force (no prompt)
Remove directory recursively.
Force recursive (DANGEROUS!)
Create directories.
Create directory.
Create nested directories.
Remove empty directories.
Remove empty directory.
Remove nested empty directories.
Create links.
Hard link (same inode)
Symbolic link (shortcut)
Symlink to directory.
rm -rf / will recursively delete your entire filesystem. Always double-check your commands, especially when using wildcards with rm.
7 File Permissions
Understanding and managing access control
Linux uses a permission-based access control system that determines who can read, write, or execute files and directories. Every file has an owner, a group, and permissions for three categories: owner, group, and others.
Permission Notation
| Permission | Numeric | Symbolic | Effect on File | Effect on Directory |
|---|---|---|---|---|
| Read | 4 | r | View contents | List files |
| Write | 2 | w | Modify contents | Create/delete files |
| Execute | 1 | x | Run as program | Enter directory |
chmod - Change Permissions
Numeric mode (owner, group, others)
Rwxr-xr-x.
Rw-r--r--.
Rwx------ (only owner)
Rwxrwxrwx (everyone)
Symbolic mode.
Add execute for owner.
Remove write for group and others.
Set read-only for all.
Set specific permissions.
Recursive.
Apply to all files and subdirectories.
Special permissions.
SUID - run as file owner.
SGID - new files inherit group.
Sticky bit - only owner can delete.
Default Permissions with umask
Check current umask.
0022 (typical default)
Calculate default permissions:
Files: 666 - umask = 644 (rw-r--r--)
Directories: 777 - umask = 755 (rwxr-xr-x)
Set umask (restrictive)
Files: 640, Directories: 750.
Make umask persistent.
8 Ownership & ACL
Managing who owns what, beyond basic permissions
Every file and directory in Linux belongs to a user owner and a group owner. Standard permission bits (owner/group/others) are often not granular enough — Access Control Lists (ACLs) extend this model to allow permissions for specific additional users or groups.
Changing Ownership
Change owner.
Set user owner.
Set user and group.
Set group only.
Recursive.
Change group only.
Reference another file's ownership.
Access Control Lists (ACL)
View ACLs.
Grant a specific user read/write access.
Grant a group execute access.
Set default ACL for a directory (inherited by new files)
Remove a specific entry.
Remove all ACL entries.
ls -l shows a + after the permission string, e.g. -rw-rw-r--+.
9 Archiving & Compression
Bundling and shrinking files for storage or transfer
Linux separates archiving (combining multiple files into one) from compression (reducing size). The tar utility handles archiving and can pipe through a compressor in the same command.
tar - Tape Archive
Create archive.
C=create v=verbose f=file.
Gzip compression.
Bzip2 (better ratio, slower)
Xz (best ratio, slowest)
Extract archive.
Extract to specific dir.
List contents without extracting.
Extract a single file.
Compression Utilities
| Tool | Extension | Command | Notes |
|---|---|---|---|
| gzip | .gz | gzip file / gunzip file.gz | Fast, moderate ratio |
| bzip2 | .bz2 | bzip2 file / bunzip2 file.bz2 | Slower, better ratio |
| xz | .xz | xz file / unxz file.xz | Best ratio, CPU intensive |
| zip | .zip | zip -r out.zip dir/ / unzip out.zip | Cross-platform friendly |
tar -czvf backup-$(date +%F).tar.gz /data in a cron job for simple dated backups.
10 grep & Regular Expressions
Searching text with pattern matching
grep (Global Regular Expression Print) searches text for lines matching a pattern. Combined with regular expressions, it becomes one of the most powerful tools in the Linux toolbox.
Basic search.
Case-insensitive.
Recursive search in directory.
Show line numbers.
Invert match (lines NOT containing pattern)
Count matches.
Show only the matched text.
Whole word match.
Extended regex (ERE) - avoids escaping +, ?, |, ()
Context lines.
3 lines After.
3 lines Before.
3 lines Context (both)
Regular Expression Basics
| Pattern | Meaning | Example |
|---|---|---|
. | Any single character | c.t → cat, cut, c9t |
* | Zero or more of previous | ab*c → ac, abc, abbc |
^ | Start of line | ^Error |
$ | End of line | done$ |
[abc] | Character class | [aeiou] |
[^abc] | Negated class | [^0-9] |
\d / [0-9] | Digit | [0-9]\+ |
+ (ERE) | One or more | a+ |
? (ERE) | Zero or one | colou?r |
| (ERE) | Alternation (OR) | cat|dog |
11 sed Stream Editor
Non-interactive text transformation
sed (Stream EDitor) processes text line by line, applying commands like substitution, deletion, or insertion — ideal for scripted, repeatable edits across files.
Substitute first match per line.
Substitute ALL matches per line (global)
Case-insensitive substitution.
Edit file in place (with backup)
Edit in place (no backup)
Delete lines matching a pattern.
Delete comment lines.
Print specific line range.
Delete a specific line number.
Insert a line before/after a match.
Multiple commands.
sed 's#/usr/local#/opt#g'.
12 awk Programming
Pattern scanning and column-based text processing
awk is a full text-processing language built around the idea of splitting each input line into fields. It excels at reports, column extraction, and quick data summaries.
Print specific columns ($1 = first field, $NF = last field)
Custom field separator (e.g. CSV)
Filter rows matching a condition.
Sum a column.
Print line count (like wc -l)
Combine pattern + action.
Print disk usage per user process (ps + awk)
NR (current record/line number), NF (number of fields on current line), FS (field separator), OFS (output field separator).
13 Pipes & Redirection
Chaining commands and controlling input/output streams
Linux gives every process three standard streams: stdin (0), stdout (1), and stderr (2). Redirection and pipes let you rewire these streams to build powerful command chains.
Pipe: send stdout of one command to stdin of next.
Redirect stdout to a file (overwrite)
Redirect stdout to a file (append)
Redirect stderr only.
Redirect both stdout and stderr.
Shorthand.
Discard output.
Redirect stdin from a file.
Here-document (multi-line stdin)
Tee: write to file AND stdout simultaneously.
Command substitution.
14 Users & Groups
Multi-user account management
Linux is a multi-user system by design. Every process runs as a specific user, and access to files is governed by that user's identity and group memberships, stored in /etc/passwd, /etc/shadow, and /etc/group.
Create a user.
-m creates home dir, -s sets shell.
Interactive, friendlier (Debian/Ubuntu)
Set / change password.
Modify a user.
Add to sudo group (-a = append, don't overwrite)
Change shell.
Lock account.
Delete a user.
Keep home directory.
Remove home directory too.
Group management.
Add user to group.
Remove user from group.
View identity and group info.
Who is logged in.
Who + what they're doing.
Key Files
| File | Contents |
|---|---|
/etc/passwd | Username, UID, GID, home dir, shell (no passwords) |
/etc/shadow | Encrypted passwords, expiration policy (root-only readable) |
/etc/group | Group names, GIDs, and member lists |
/etc/sudoers | Rules for who can use sudo and how |
15 sudo & Privileges
Controlled privilege escalation
sudo ("superuser do") lets authorized users run commands as another user — typically root — without sharing the root password, while logging every invocation for accountability.
Run a single command as root.
Run as a specific user.
Open a root shell.
Edit sudoers safely (validates syntax before saving)
Check what you're allowed to run.
Re-run the previous command with sudo.
sudoers Syntax
/etc/sudoers - format: user host=(runas) commands.
Full sudo access.
No password prompt.
Group, one command only.
/etc/sudoers with visudo, never directly — a syntax error can lock you out of privilege escalation entirely.
16 SSH & Remote Access
Secure remote administration
SSH (Secure Shell) provides encrypted remote login and file transfer, replacing insecure protocols like telnet and rsh. It underpins virtually all remote Linux server administration.
Connect to a remote host.
Custom port.
Specific key.
Generate a key pair.
Copy public key to server for passwordless login.
Copy files over SSH.
Faster, incremental.
Run a remote command without an interactive shell.
Port forwarding (tunnel local port to remote service)
SSH Config File
Save per-host shortcuts to ~/.ssh/config instead of typing the full connection details each time.
With that alias defined, connecting is as simple as:
SSH reads the host, user, port, and key from the config file automatically.
/etc/ssh/sshd_config (PasswordAuthentication no) once key-based login works, to shut down brute-force attempts entirely.
17 Processes & Jobs
Monitoring and controlling running programs
Every running program is a process with a unique Process ID (PID). Linux provides rich tooling to inspect, prioritize, and manage processes, plus job control for foreground/background execution within a shell session.
View running processes.
All processes, all users.
Full-format listing.
Find a specific process.
Interactive real-time monitor.
Nicer UI (install separately)
Process tree.
Job control.
Run in background.
List background jobs.
Bring job 1 to foreground.
Resume job 1 in background.
Suspend current foreground job.
Keep a process running after logout.
Change process priority (nice value: -20 highest, 19 lowest)
18 Signals & Kill
Communicating with and terminating processes
Signals are the kernel's way of notifying a process of an event — from a graceful termination request to an immediate, unstoppable kill.
| Signal | Number | Meaning |
|---|---|---|
SIGHUP | 1 | Hangup — often used to reload config |
SIGINT | 2 | Interrupt (Ctrl+C) |
SIGKILL | 9 | Force kill — cannot be caught or ignored |
SIGTERM | 15 | Graceful termination request (default) |
SIGSTOP | 19 | Pause process — cannot be caught |
SIGCONT | 18 | Resume a stopped process |
Send SIGTERM (graceful) by PID.
Force kill.
Kill by process name.
Send signal to all jobs in current shell.
List available signals.
SIGTERM (default) over SIGKILL whenever possible — it gives the process a chance to close files and clean up. Reserve -9 for unresponsive processes.
19 Cron & Scheduling
Automating recurring tasks
cron is a time-based job scheduler that runs commands automatically at specified intervals, defined per-user in a crontab file.
Edit your crontab.
List your crontab.
Remove your crontab.
Format: minute hour day month weekday command.
Daily at 3:00 AM.
Every 15 minutes.
Every Sunday at midnight.
1st of every month, 9:30 AM.
systemd Timers (Modern Alternative)
A timer unit (/etc/systemd/system/backup.timer) pairs with a matching .service unit of the same name to schedule it.
Enable the timer and confirm it's scheduled.
Enables the timer at boot and starts it immediately.
Lists active timers and when each will next run.
journalctl automatically and support dependency ordering — worth adopting for anything beyond simple schedules.
20 Network Commands
Diagnosing and configuring connectivity
Interface configuration (modern)
Show all addresses.
Show interfaces.
Show routing table.
Connectivity testing.
4 packets.
Path to destination.
Continuous traceroute + ping.
Open connections and listening ports.
Modern replacement for netstat.
Download files.
Test an HTTP endpoint.
Headers only.
Verbose (show handshake)
Show/renew DHCP lease.
21 Firewall & iptables
Filtering network traffic
Linux firewalling is built on the kernel's netfilter framework. iptables is the classic low-level tool; ufw and firewalld are friendlier front-ends built on top of it (or nftables).
ufw (Uncomplicated Firewall — Debian/Ubuntu)
Allow SSH.
firewalld (RHEL/Fedora)
iptables (Low-Level)
List current rules.
Allow incoming SSH.
Drop all other incoming traffic.
Save rules (Debian/Ubuntu, via iptables-persistent)
22 DNS & Hostname
Name resolution and host identity
Query DNS records.
Mail records.
Just the IP.
Reverse lookup.
Hostname management.
Show current hostname.
Local name resolution (checked before DNS)
127.0.0.1 localhost.
192.168.1.5 web01.local web01.
DNS resolver configuration.
/etc/nsswitch.conf — the hosts: line typically reads files dns, meaning /etc/hosts is checked first.
23 APT (Debian/Ubuntu)
Package management on Debian-based distributions
Update package index.
Upgrade installed packages.
Also handles dependency changes/removals.
Install / remove packages.
Keep config files.
Remove config files too.
Remove unused dependencies.
Search and info.
List installed packages.
List files owned by package.
Install a local .deb file.
Fix missing dependencies afterward.
Hold a package at its current version.
24 DNF/YUM (RHEL/Fedora)
Package management on Red Hat-based distributions
dnf is the modern successor to yum, used on Fedora, RHEL 8+, CentOS Stream, AlmaLinux, and Rocky Linux.
Update package index and packages.
Install / remove.
Search and info.
List installed packages.
List files owned by package.
Install a local .rpm file.
Manage repositories.
Groups of related packages.
25 Pacman (Arch)
Package management on Arch Linux and derivatives
Sync repo index and upgrade whole system (do together, always)
Install a package.
Remove a package.
Keep dependencies.
Remove unused dependencies too.
Search.
Info.
Remote package info.
Installed package info.
List installed packages.
Explicitly installed (not deps)
Clean package cache.
AUR helper (not part of pacman itself)
pacman -Sy (sync only) without -u right after — a partial upgrade can break dependency resolution on a rolling-release system.
26 Snap, Flatpak & AppImage
Distribution-agnostic packaging formats
These formats bundle an application with its dependencies so it runs consistently across distributions, at the cost of larger download sizes and slightly slower startup.
Snap (Canonical)
Flatpak (community/Red Hat backed)
AppImage - single portable executable, no install needed.
| Format | Sandboxing | Backed By | Typical Use |
|---|---|---|---|
| Snap | Yes (strict confinement) | Canonical | Ubuntu desktop & server apps |
| Flatpak | Yes (portals) | Community, GNOME/KDE | Desktop GUI apps |
| AppImage | No | Community | Portable, no-install apps |
27 systemd & Services
The modern init system and service manager
systemd is PID 1 on nearly all modern distributions — it boots the system, manages services (units), handles logging, and coordinates dependencies between them.
Service control.
Reload config without downtime.
Enable/disable at boot.
Enable and start immediately.
List units.
Check if active/enabled.
Writing a Custom Unit File
A minimal service unit for a long-running app, saved as /etc/systemd/system/myapp.service.
After creating or editing a unit file, reload systemd's configuration and start the service.
Tells systemd to re-read unit files, picking up new or changed ones.
Enables the service at boot and starts it right away.
28 journalctl & Logs
Reading the systemd journal
journalctl queries the binary, structured logs collected by journald — covering the kernel, services, and boot process in one unified place.
View all logs (oldest first)
Follow logs live (like tail -f)
Logs for a specific service.
Logs since a given time.
Logs from the current boot only.
Filter by priority (0=emerg ... 7=debug)
Kernel messages only.
Limit disk usage of the journal.
/var/log (e.g. /var/log/syslog, /var/log/auth.log), readable directly with tail, less, or grep.
29 Kernel Modules
Extending kernel functionality at runtime
Loadable Kernel Modules (LKMs) add drivers and functionality to a running kernel without a reboot — most hardware drivers and filesystems are implemented this way.
List loaded modules.
Show details about a module.
Load / unload a module.
Remove (and unused dependencies)
Load directly from file (no dependency resolution)
Persist a module across reboots.
Blacklist a module (prevent auto-load)
Kernel version and info.
Recent kernel ring buffer messages.
30 Disk & Storage
Partitioning, filesystems, and monitoring space
Disk usage overview.
Free/used space per mounted filesystem.
Directory size breakdown.
Total size of a directory.
Per-subdirectory sizes.
List block devices and partitions.
Partition a disk (interactive)
Create a filesystem.
Mount / unmount.
Persistent mounts (edit carefully!)
UUID=xxxx /mnt/data ext4 defaults 0 2.
Check and repair a filesystem (must be unmounted)
Logical Volume Manager (LVM) basics.
blkid and use it in /etc/fstab instead of a device name like /dev/sdb1, since device names can shift between boots.
31 Bash Basics
Writing your first shell scripts
A shell script is a text file of commands executed in sequence by an interpreter, declared via a shebang line. Scripts automate repetitive administration tasks. Here's a simple deployment script, saved as deploy.sh:
Make it executable and run it.
Or run without executable bit.
Strict mode - fail fast on errors (recommended at top of scripts)
-e: exit on any error -u: error on unset variables -o pipefail: catch errors in pipes.
32 Variables & Expansion
Storing and manipulating data in shell scripts
Declare and use variables (no spaces around =)
Braces avoid ambiguity.
Command output into a variable.
Arithmetic.
Arrays.
All elements.
Array length.
Default values / parameter expansion.
Use default if unset.
String length.
Substitution.
Special variables.
Script name.
First and second arguments.
Number of arguments.
All arguments.
Exit code of last command.
PID of current script.
33 Conditionals & Loops
Control flow in shell scripts
An if/elif/else block branches on the exit status of a test. Each condition is tried in order until one succeeds.
A one-line form works for a single string comparison.
Runs the command only if $name equals "Alice".
File test operators check whether a path exists and what kind of file it is, without needing to open it.
-f is true if the path exists and is a regular file.
-d is true if the path exists and is a directory.
A for loop iterates over a fixed list of words or values.
A glob pattern in the list lets the loop walk over matching files.
C-style for loops give explicit control over the counter, using an initializer, a condition, and an increment.
A while loop keeps running as long as its test succeeds.
A case statement matches a value against several patterns, similar to a switch statement in other languages.
34 Functions
Reusable blocks of shell logic
Define a function by name, then call it like any other command. local scopes a variable to the function so it doesn't leak into the rest of the script.
A function can return a value through its exit code — but only as an integer from 0 to 255, since that's all an exit code can hold. By convention 0 means success/true and anything else means failure/false.
To return an actual value (not just success/failure), the common pattern is to echo it and capture the output with command substitution.
The ${1:-default} expansion gives a parameter a default value when the caller doesn't provide one.
35 Security Basics
Hardening a Linux system
Linux security is layered: user privilege separation, filesystem permissions, network filtering, and mandatory access control all work together. A few practices cover most of the risk for a typical server.
- Keep the system updated:
apt upgrade/dnf upgraderegularly, or enable unattended security updates. - Disable root SSH login: set
PermitRootLogin noin/etc/ssh/sshd_config. - Use key-based SSH auth and disable password authentication once configured.
- Principle of least privilege: grant only the permissions and sudo rights a user or service actually needs.
- Enable a firewall and only open the ports you actually use.
- Use fail2ban to auto-ban IPs after repeated failed login attempts.
Install and enable fail2ban.
Audit listening ports (attack surface)
Check for failed login attempts.
Failed login history.
Check for world-writable files (common misconfiguration)
36 SELinux & AppArmor
Mandatory Access Control (MAC) systems
Standard permissions are discretionary — the owner decides access. SELinux (Red Hat family) and AppArmor (Debian/Ubuntu/SUSE family) add mandatory access control: even root can be confined by policy.
SELinux
Check current mode.
Enforcing / Permissive / Disabled.
Temporarily change mode (until reboot)
Permissive (log only, don't block)
Enforcing.
View file/process context labels.
Restore default context after moving a file.
View recent denials.
AppArmor
Status of all profiles.
Put a profile into complain (log-only) or enforce mode.
37 Encryption & Keys
Protecting data at rest and in transit
Full-disk / partition encryption with LUKS.
File/text encryption with GPG.
Symmetric (password-based)
Decrypt.
Generate a checksum to verify integrity.
TLS certificates (Let's Encrypt via certbot)
cryptsetup luksHeaderBackup) — losing it makes the encrypted data unrecoverable even with the correct passphrase.
38 Containers & Docker
Lightweight, isolated application environments
Containers package an application with its dependencies using kernel features like namespaces (isolation) and cgroups (resource limits) — no separate guest kernel required, unlike a VM.
Run a container.
List running / all containers.
Stop, start, remove.
Logs and shell access.
Images.
Clean up unused resources.
Dockerfile Basics
A Dockerfile describes how to build an image, step by step, layer by layer.
Docker Compose
Compose defines multiple related containers — here a web app and its database — as one file.
Builds and starts every service defined in the file, in the background.
39 Virtualization
Running full virtual machines on Linux
Unlike containers, virtual machines run their own complete kernel via a hypervisor. Linux's built-in hypervisor is KVM (Kernel-based Virtual Machine), usually driven through QEMU and managed with libvirt.
Check for hardware virtualization support.
Install KVM/QEMU + libvirt tooling (Debian/Ubuntu)
Manage VMs with virsh.
Force power off.
Create a VM from the command line.
| Aspect | Containers | Virtual Machines |
|---|---|---|
| Kernel | Shared with host | Own dedicated kernel |
| Startup time | Milliseconds to seconds | Seconds to minutes |
| Isolation strength | Process-level | Hardware-level |
| Overhead | Low | Higher (full OS per VM) |
40 Performance Tuning
Diagnosing and improving system performance
CPU load and averages.
Load averages: 1, 5, 15 min.
Live CPU/memory/IO stats.
Per-core CPU usage.
Memory usage.
Disk I/O.
Per-process disk I/O (like top)
Find what's consuming the most CPU/memory.
Trace open files and syscalls of a process.
Network throughput.
iowait in vmstat points to disk I/O instead — diagnose before you tune.