IN·79
Linux
Linux for engineers who run software on it: the kernel/user-space boundary and system calls, the filesystem hierarchy, VFS, inodes and links, permissions (modes, umask, setuid, ACLs, capabilities), users and groups, processes (fork/exec, states, signals, file descriptors, limits), systemd units, journald and timers, the environment, logging, networking (interfaces, routes, sockets, DNS, nftables, diagnostics), package management, storage (block devices, LVM, filesystems, page cache, fsync), and CPU, memory and I/O diagnostics with the USE method, with how Java, Go, Rust, Python, C and Zig programs interact with each piece.
Start here: users, files and processes
Everything has an owner and permissions
Linux is a multi-user system: every file belongs to a user and a group, and carries permission bits for the owner, the group and everyone else.
$ id; ls -l /etc/shadow /etc/passwd
uid=0(root) gid=0(root) groups=0(root)
-rw-r--r-- 1 root root 3437 Oct 30 04:10 /etc/passwd
-rw-r----- 1 root shadow 1423 Oct 30 04:10 /etc/shadow
Read -rw-r----- as three groups of three after the file type: owner rw- (read, write), group r-- (read), others --- (nothing). /etc/passwd (account names) is readable by all; /etc/shadow (password hashes) only by root and the shadow group. Apply the same idea to an application secret:
$ ls -l /srv/tiffin/app.env; su meena -c "cat /srv/tiffin/app.env"
-rw-r----- 1 root root 19 Oct 30 04:23 /srv/tiffin/app.env
cat: /srv/tiffin/app.env: Permission denied
The user meena is neither the owner nor in the group, so the kernel refused. Services should run as their own unprivileged user that can read their configuration and nothing else; root bypasses these checks, which is why running services as root is dangerous.
A process, seen from the outside
Start the service and look at it through /proc, the kernel's window onto every process:
$ grep -E '^(Name|State|PPid|Uid|VmRSS|Threads)' /proc/30276/status
Name: tiffin
State: S (sleeping)
PPid: 30258
Uid: 0 0 0 0
VmRSS: 5336 kB
Threads: 7
$ ls -l /proc/30276/fd
0 -> /dev/null
1 -> /tmp/V6/c79/t.log
2 -> /tmp/V6/c79/t.log
3 -> socket:[89897]
5 -> anon_inode:[eventpoll]
6 -> anon_inode:[eventfd]
$ ss -tlnp | grep 8080
LISTEN 0 4096 0.0.0.0:8080 0.0.0.0:* users:(("tiffin",pid=30276,fd=3))
The process is sleeping (waiting for requests), uses 5.3 MB of real memory (RSS), runs 7 threads (Go's runtime), and has file descriptors: 0, 1 and 2 are standard input, output and error (here redirected to a log file), 3 is its listening socket, and 5–6 are the event-polling machinery that lets one thread wait on thousands of connections. ss confirms that file descriptor 3 is the socket listening on port 8080. "Everything is a file" in Linux means exactly this: files, sockets, pipes and devices are all reached through descriptors.
Signals: asking a process to stop
$ kill -TERM 30276; cat t.log
exit status: 0
tiffin v1 listening on :8080 (pid 30276)
got terminated, draining for up to 10s
stopped cleanly
kill sends a signal. SIGTERM (15) asks politely: the program caught it, finished in-flight requests and exited with status 0. SIGINT (2) is Ctrl-C. SIGKILL (9) can't be caught: the kernel removes the process immediately, with no cleanup. Service managers (systemd, Docker, Kubernetes) all send SIGTERM first, wait a grace period, then SIGKILL, so every service should handle SIGTERM.
| Command | What it shows |
|---|---|
ps -ef, top, htop |
Processes, their parents, CPU and memory |
ss -tlnp |
Listening TCP sockets and their processes |
df -h, du -sh |
Disk space by filesystem, by directory |
free -m |
Memory, including page cache (buff/cache) |
journalctl -u name |
A systemd service's logs |
ls -l /proc/PID/fd |
A process's open files and sockets |
How deep to go in Linux
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Navigate the filesystem; read permissions; list processes, ports and disk usage |
| L2 | Manage users, permissions, services (systemd), packages and logs on a server |
| L3 | Explain processes, signals, file descriptors, the page cache, memory accounting and networking |
| L4 | Diagnose full disks, fd exhaustion, OOM kills, high load, slow I/O and port conflicts |
| L5 | Design hardened, observable host configurations and service units for a fleet |
| L6 | Tune kernels and operate fleets with eBPF tooling, capacity planning and patching at scale |
The shape of a Linux system
Kernel and user space
Linux is a kernel: the privileged program that manages hardware, memory, processes, filesystems and networking. Everything else (shells, systemd, databases, your Java or Go service) runs in user space and asks the kernel for services through system calls (read, write, openat, clone, execve, mmap, socket, epoll_wait…). A "distribution" (Debian, Ubuntu, Fedora, RHEL and its rebuilds, Alpine, Arch) is the kernel plus a user space: C library (glibc or musl), init system, package manager, tools.
You can watch the boundary directly: strace -f -e trace=openat,read,write,connect java -jar app.jar lists every system call. Languages hide syscalls behind their standard libraries, but performance and failure behaviour (blocking I/O, file descriptor exhaustion, EINTR, EAGAIN) come straight from them.
| Language | How it reaches the kernel |
|---|---|
| C | glibc/musl wrappers (open, read), or raw syscall(2) |
| C++ | C library plus <filesystem>, <thread> |
| Zig | std.posix / std.os.linux make syscalls directly (no libc required), or link libc |
| Rust | std via libc (or rustix for direct syscalls); nix crate for POSIX APIs |
| Go | Runtime makes syscalls directly on Linux (no libc unless cgo is used); its netpoller uses epoll |
| Java | JVM native code over glibc; NIO selectors over epoll; virtual threads park on the poller |
| Python | CPython over libc; os module exposes many syscalls almost 1:1 |
Boot in one paragraph
Firmware (UEFI) loads a bootloader (GRUB, systemd-boot), which loads the kernel and an initramfs (a small early root filesystem with drivers needed to find the real root). The kernel mounts the root filesystem and starts PID 1, which on almost every distribution is systemd. systemd starts everything else, in parallel, by dependency.
The filesystem
Everything is a file (mostly)
Linux presents one tree rooted at /. Disks, partitions, network shares and virtual filesystems are mounted onto directories in that tree. The Filesystem Hierarchy Standard defines where things go:
| Path | Contents |
|---|---|
/bin, /sbin, /lib |
Now usually symlinks into /usr ("usrmerge") |
/usr |
Installed software: /usr/bin, /usr/lib, /usr/share; read-only in principle |
/usr/local, /opt |
Locally installed software outside the package manager |
/etc |
System configuration (text files) |
/var |
Variable data: /var/log, /var/lib (databases, Docker), /var/cache, /var/spool |
/home, /root |
User home directories |
/tmp, /var/tmp |
Temporary files (/tmp is often RAM-backed tmpfs, cleaned at boot) |
/run |
Runtime state since boot (PID files, sockets), tmpfs |
/dev |
Device files (/dev/nvme0n1, /dev/null, /dev/urandom) managed by udev |
/proc |
Virtual: process and kernel information (/proc/<pid>/status, /proc/meminfo) |
/sys |
Virtual: kernel objects, devices, cgroups (/sys/fs/cgroup) |
/boot |
Kernel, initramfs, bootloader files |
/proc and /sys don't exist on disk: reading them runs kernel code. They're how tools like ps, top, free and container runtimes get their information, and how you tune the kernel (/proc/sys/net/core/somaxconn, set persistently with sysctl files in /etc/sysctl.d/).
VFS, inodes and directory entries
The Virtual File System gives one API (open, read, stat…) over many filesystem types (ext4, XFS, Btrfs, tmpfs, NFS, overlayfs, procfs). Its key objects:
- Inode: the file's metadata and data location: type, permissions, owner, size, timestamps, link count, block pointers. Not its name.
- Directory entry (dentry): a mapping name → inode number inside a directory. A directory is just a file containing such entries.
- Open file description: created by
open, holding the current offset and flags; shared afterforkordup. - File descriptor: a small integer in a process's table pointing to an open file description. 0, 1, 2 are stdin, stdout, stderr.
Consequences you meet in practice:
- Hard links (
ln a b) are two names for one inode; both are equal. They can't cross filesystems or point to directories. - Symbolic links (
ln -s target name) store a path; they can dangle. Atomic deployments flip acurrentsymlink:ln -sfn releases/v43 current.tmp && mv -T current.tmp current(rename is atomic). - Deleting a file that's open removes its name, but the space isn't freed until every descriptor closes. "Disk full, but
dushows nothing" usually means a process still holds a deleted log file:lsof +L1finds it. - Running out of inodes (millions of tiny files) gives "No space left on device" while
df -hshows free space: checkdf -i. renameis atomic within a filesystem: the safe way to replace a file is write a temp file,fsyncit,renameover the old one, andfsyncthe directory.
Mounts
mount attaches a filesystem to a directory. /etc/fstab lists mounts at boot (prefer UUID= or LABEL= to device names, which can change). Useful options: noatime (don't update access times on reads), ro, nosuid, nodev, noexec (hardening /tmp and data volumes). findmnt shows the mount tree. Bind mounts (mount --bind /src /dst) make a directory appear in a second place, which is how containers get volumes. Mount namespaces give each container its own mount table (chapter 80).
Permissions
Users, groups and IDs
The kernel knows only numbers: a UID (user ID) and GIDs (group IDs). Names come from /etc/passwd (user name, UID, primary GID, home, shell) and /etc/group; password hashes live in /etc/shadow (root-readable only). Directory services (LDAP, FreeIPA, Active Directory via SSSD) can supply the same information.
- root is UID 0. Traditionally it bypasses permission checks; modern kernels split root's power into capabilities (below).
- System users (UIDs below 1000 by convention) run services:
postgres,nginx,www-data. Services should never run as root unless they truly must. idshows your UID, GIDs and groups;sudoruns a command as another user (usually root) according to/etc/sudoers(edit withvisudo, or drop files in/etc/sudoers.d/).- Commands:
useradd -r -s /usr/sbin/nologin svc(system user without login),usermod -aG docker alice(add to group; note thatdockergroup membership is root-equivalent),passwd,chage(password ageing).
Because files store numeric IDs, UID 1000 inside a container or on an NFS server is the same "owner" as UID 1000 on the host, even if the names differ. Mismatched UIDs are the usual cause of "permission denied" on mounted volumes.
Mode bits
Every inode has an owner UID, a group GID and mode bits: read (r=4), write (w=2) and execute (x=1) for user (owner), group and others.
-rwxr-x--- 1 deploy app 1234 Oct 24 10:00 run.sh
│└┬┘└┬┘└┬┘
│ │ │ └─ others: --- (0)
│ │ └──── group: r-x (5)
│ └─────── user: rwx (7) → octal 0750
└───────── type: - file, d directory, l symlink, c/b char/block device, s socket, p pipe
Meaning differs for directories: r lists names, w creates, deletes and renames entries (regardless of the files' own permissions!), x lets you traverse into it and access entries by name. To read /srv/app/config.yml you need x on /, /srv and /srv/app, and r on the file.
The check is: if you're the owner, use the user bits; else if you're in the group, use the group bits; else use others. It doesn't fall through: an owner with --- is denied even if others have rwx.
chmod 640 file,chmod u+x,g-w file,chmod -R(careful).chown user:group file(changing owner requires root orCAP_CHOWN).- umask removes bits from newly created files: with umask
022, a new file gets0644(from 0666) and a directory0755(from 0777). Services often setUMask=0027.
Special bits
| Bit | On files | On directories |
|---|---|---|
setuid (4000, s in user x) |
Program runs with the file owner's UID (e.g. passwd, sudo run as root) |
Ignored on Linux |
| setgid (2000) | Runs with the file's group | New entries inherit the directory's group (shared team directories) |
sticky (1000, t) |
Ignored | Only the owner of an entry may delete or rename it (/tmp is 1777) |
setuid-root binaries are prime attack targets; find them with find / -perm -4000 -type f 2>/dev/null and mount data volumes nosuid.
ACLs and capabilities
- POSIX ACLs grant permissions to additional users and groups:
setfacl -m u:bob:rx /srv/app,getfacl. A+after the mode inls -lsignals an ACL. - Linux capabilities split root's privileges into about 40 units:
CAP_NET_BIND_SERVICE(bind ports below 1024),CAP_CHOWN,CAP_SYS_ADMIN(a huge grab-bag, nearly root),CAP_NET_ADMIN,CAP_SYS_PTRACE… A process (or a file, viasetcap) can hold only the ones it needs. Containers run with a reduced capability set (chapter 81).
# Let a non-root binary bind port 443 without running as root
sudo setcap 'cap_net_bind_service=+ep' /usr/local/bin/myserver
getcap /usr/local/bin/myserver
# Or, in a systemd unit: AmbientCapabilities=CAP_NET_BIND_SERVICE
Mandatory access control
Beyond these discretionary controls, SELinux (RHEL family, Android) and AppArmor (Ubuntu, Debian, SUSE) enforce system-wide policies that even root processes must obey: a confined nginx can't read /home regardless of file modes. "Permission denied" with correct modes often means SELinux: check ausearch -m avc or journalctl -t setroubleshoot, and fix contexts with restorecon / semanage fcontext rather than disabling SELinux.
Processes
Creating processes: fork and exec
A process is a running program: an address space, one or more threads, open file descriptors, credentials, a current directory, signal handlers, resource limits and namespace/cgroup membership.
Unix creates processes in two steps:
fork()(orclone()) duplicates the calling process. The child gets a copy of the address space (shared copy-on-write, so it's cheap), copies of file descriptors, and the same code;forkreturns the child's PID to the parent and 0 to the child.execve(path, argv, envp)replaces the current program with a new one: new code and memory, same PID, file descriptors kept (unless marked close-on-exec).
The shell runs ls by forking itself, then the child execs /usr/bin/ls, and the parent waits (waitpid) for its exit status. Modern runtimes often use posix_spawn or clone with CLONE_VM | CLONE_VFORK to avoid copying large address spaces (the JVM's ProcessBuilder and Go's os/exec do this).
// C: fork + exec + wait, the primitive behind every process launch
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
pid_t pid = fork();
if (pid == 0) { // child
execlp("ls", "ls", "-l", "/srv", (char *)NULL);
perror("exec"); _exit(127); // only reached if exec failed
}
int status;
waitpid(pid, &status, 0); // parent reaps the child
printf("exit code %d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
}
// Go: os/exec (uses clone/exec under the hood); context kills the child on timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, "ls", "-l", "/srv").CombinedOutput()
var ee *exec.ExitError
if errors.As(err, &ee) { fmt.Println("exit code", ee.ExitCode()) }
fmt.Print(string(out))
// Java: ProcessBuilder; always drain or redirect output or the child can block on a full pipe
Process p = new ProcessBuilder("ls", "-l", "/srv")
.redirectErrorStream(true)
.start();
String out = new String(p.getInputStream().readAllBytes());
boolean done = p.waitFor(5, TimeUnit.SECONDS);
int code = done ? p.exitValue() : -1;
// Rust: std::process::Command
use std::process::Command;
let out = Command::new("ls").args(["-l", "/srv"]).output()?;
println!("exit {:?}\n{}", out.status.code(), String::from_utf8_lossy(&out.stdout));
# Python: subprocess.run (never shell=True with untrusted input)
import subprocess
r = subprocess.run(["ls", "-l", "/srv"], capture_output=True, text=True, timeout=5)
print(r.returncode, r.stdout)
// Zig: std.process.Child
const std = @import("std");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const alloc = gpa.allocator();
const r = try std.process.Child.run(.{ .allocator = alloc, .argv = &.{ "ls", "-l", "/srv" } });
defer { alloc.free(r.stdout); alloc.free(r.stderr); }
std.debug.print("{s}", .{r.stdout});
}
Process states and the process tree
Every process has a PID and a parent PID; the tree is rooted at PID 1 (pstree -p, ps -ef --forest).
State (ps STAT) |
Meaning |
|---|---|
| R | Running or runnable (on a CPU or in the run queue) |
| S | Interruptible sleep: waiting for an event (socket data, timer) |
| D | Uninterruptible sleep: usually waiting on disk or NFS I/O; can't be killed until the I/O returns. Many D processes mean storage trouble |
| T | Stopped (SIGSTOP, or a debugger) |
| Z | Zombie: exited, but the parent hasn't called wait to collect its status. Uses no memory, only a PID slot |
Zombies and orphans: if a parent dies, its children are re-parented to PID 1 (or the nearest "subreaper"), which must reap them. In containers your app is often PID 1 and won't reap grandchildren, so zombies accumulate; that's why containers use a tiny init such as tini (Docker's --init), or set the app to reap children.
Signals
Signals are asynchronous notifications to a process:
| Signal | Default | Typical meaning |
|---|---|---|
SIGTERM (15) |
Terminate | "Please shut down gracefully": what kill, systemd and Kubernetes send first |
SIGKILL (9) |
Terminate, can't be caught | Forced kill; no cleanup. Sent after a grace period, or by the OOM killer |
SIGINT (2) |
Terminate | Ctrl+C |
SIGHUP (1) |
Terminate | Terminal closed; by convention, daemons reload config on it |
SIGQUIT (3) |
Core dump | Ctrl+\; the JVM prints a thread dump instead |
SIGCHLD |
Ignore | A child changed state (time to wait) |
SIGSTOP / SIGCONT |
Stop / continue | Can't be caught |
SIGPIPE |
Terminate | Wrote to a pipe or socket whose reader is gone |
SIGSEGV, SIGBUS, SIGFPE |
Core dump | Invalid memory access, bus error, arithmetic error |
SIGUSR1, SIGUSR2 |
Terminate | Application-defined |
Graceful shutdown is one of the most important behaviours of a service on Linux, in containers and in Kubernetes: on SIGTERM, stop accepting new work, finish in-flight requests within a deadline, flush and close, then exit 0. Note that PID 1 gets no default signal handlers from the kernel: a process running as PID 1 that doesn't install a SIGTERM handler simply ignores SIGTERM, and is SIGKILLed after the grace period.
// Go: graceful HTTP shutdown on SIGTERM/SIGINT
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
srv := &http.Server{Addr: ":8080", Handler: mux}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatal(err) }
}()
<-ctx.Done() // signal received
shutdownCtx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
_ = srv.Shutdown(shutdownCtx) // stop listening, drain in-flight requests
// Java: shutdown hooks run on SIGTERM/SIGINT (not on SIGKILL).
// Spring Boot: server.shutdown=graceful + spring.lifecycle.timeout-per-shutdown-phase=25s does this for you.
Runtime.getRuntime().addShutdownHook(Thread.ofPlatform().unstarted(() -> {
server.stopAccepting();
server.awaitInFlight(Duration.ofSeconds(25));
pool.close();
}));
// Rust (tokio + axum): graceful shutdown future
async fn shutdown_signal() {
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).unwrap();
tokio::select! { _ = term.recv() => {}, _ = tokio::signal::ctrl_c() => {} }
}
axum::serve(listener, app).with_graceful_shutdown(shutdown_signal()).await?;
# Python (asyncio): translate SIGTERM into an orderly shutdown
import asyncio, signal
async def main():
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for s in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(s, stop.set)
server = await start_server()
await stop.wait()
server.close(); await server.wait_closed() # drain, then exit
asyncio.run(main())
// C: sigaction sets a flag; the main loop checks it (only async-signal-safe work in handlers!)
static volatile sig_atomic_t stopping = 0;
static void on_term(int sig) { (void)sig; stopping = 1; }
int main(void) {
struct sigaction sa = { .sa_handler = on_term };
sigemptyset(&sa.sa_mask);
sigaction(SIGTERM, &sa, NULL);
while (!stopping) serve_one();
drain_and_close();
}
File descriptors and resource limits
Each process has limits (ulimit -a, /proc/<pid>/limits, prlimit):
RLIMIT_NOFILE: maximum open file descriptors (files and sockets). A busy server with the old default soft limit of 1024 fails with "Too many open files" (EMFILE). Raise it in the systemd unit (LimitNOFILE=) or container runtime. The JVM raises its soft limit to the hard limit at startup on Linux; Go has done the same since 1.19.RLIMIT_NPROC(processes/threads per user),RLIMIT_CORE(core dump size),RLIMIT_STACK,RLIMIT_MEMLOCK.- System-wide:
fs.file-max,kernel.pid_max,kernel.threads-max.
ls -l /proc/<pid>/fd and lsof -p <pid> show what a process has open: invaluable for leaks.
Scheduling and priority
The scheduler shares CPUs among runnable threads. Linux used CFS (Completely Fair Scheduler) until 6.6 and now uses EEVDF: each thread gets a share weighted by its nice value (−20 highest priority to 19 lowest; nice -n 10 cmd, renice). Real-time policies (SCHED_FIFO, SCHED_RR, chrt) preempt normal threads. taskset / sched_setaffinity pin threads to CPUs. cgroups (chapter 80) limit CPU for groups of processes; this is how containers get CPU limits, and why a container can be throttled even when the machine is idle.
systemd
Units
systemd is PID 1 on most distributions. It starts and supervises services, mounts filesystems, manages logging (journald), timers, sockets, and puts each service in its own cgroup (so it can account resources and kill every process of a service reliably). Everything is a unit:
| Unit type | Purpose |
|---|---|
.service |
A daemon or one-shot command |
.socket |
A listening socket; starts the service on first connection (socket activation) |
.timer |
Scheduled activation (cron replacement) |
.target |
A group / synchronisation point (multi-user.target, network-online.target) |
.mount, .automount |
Filesystems |
.path |
Activate on file changes |
.slice |
A cgroup grouping for resource control |
Unit files live in /usr/lib/systemd/system/ (packages) and /etc/systemd/system/ (admin overrides, which win). systemctl edit app.service creates a drop-in override in /etc/systemd/system/app.service.d/ instead of editing the vendor file.
# /etc/systemd/system/orders.service: a hardened service for a JVM, Go or Rust binary
[Unit]
Description=Orders API
Wants=network-online.target
After=network-online.target postgresql.service
[Service]
Type=simple # or Type=notify if the app calls sd_notify(READY=1)
User=orders
Group=orders
WorkingDirectory=/opt/orders
EnvironmentFile=/etc/orders/orders.env
ExecStart=/opt/orders/bin/orders --port 8080
Restart=on-failure
RestartSec=2s
TimeoutStopSec=30s # SIGTERM, then SIGKILL after 30 s
LimitNOFILE=65536
MemoryMax=1G # cgroup limits
CPUQuota=200%
# Sandboxing
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
ReadWritePaths=/var/lib/orders
CapabilityBoundingSet=
AmbientCapabilities=
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload # after changing unit files
sudo systemctl enable --now orders # start now and at boot
systemctl status orders # state, recent logs, cgroup process tree
sudo systemctl restart orders
systemctl list-units --failed
systemd-analyze security orders # scores the sandboxing of a unit
systemd-analyze blame # what slowed boot
Key ideas:
- Dependencies vs ordering are separate:
Wants=/Requires=pull units in;After=/Before=only order them. You usually need both. Restart=gives supervision (like a tiny Kubernetes for one host), with rate limiting viaStartLimitIntervalSec/StartLimitBurst.Type=notifylets the service tell systemd when it's actually ready (sd_notify), so dependants start at the right time.DynamicUser=yesallocates a throwaway UID per service.- Timers replace cron with logging, dependencies,
Persistent=true(catch up on missed runs) and randomised delays:
# /etc/systemd/system/cleanup.timer (+ a matching cleanup.service)
[Timer]
OnCalendar=*-*-* 03:15:00
RandomizedDelaySec=10m
Persistent=true
[Install]
WantedBy=timers.target
The environment
Every process inherits an environment: a list of KEY=value strings passed by execve. Shells add variables from startup files:
- Login shells read
/etc/profile, then~/.bash_profile/~/.profile; interactive non-login shells read~/.bashrc. zsh uses~/.zshenv,~/.zprofile,~/.zshrc. export VAR=valuemakes a shell variable part of the environment of child processes; plainVAR=valuedoesn't.PATHis searched left to right for commands;which -a,type,command -vshow what runs.env,printenv, and/proc/<pid>/environ(NUL-separated) show a process's environment.- Services don't read your shell profile. systemd units get only what you set with
Environment=/EnvironmentFile=; cron gets a minimal environment. "Works in my shell, fails as a service" is usually a missing variable orPATH. - Locale (
LANG,LC_ALL) affects sorting, number formats and encodings:C.UTF-8is a safe default for services. - Secrets in environment variables are convenient (twelve-factor config) but visible to anything that can read
/proc/<pid>/environas the same user, inherited by child processes, and often dumped in crash reports. Prefer files with tight permissions, systemd credentials (LoadCredential=), or a secrets manager for sensitive values.
Logs
journald and syslog
- systemd-journald captures stdout/stderr of services, kernel messages and syslog, stored in a structured, indexed binary journal (
/var/log/journal/when persistent). journalctl:-u orders(one unit),-f(follow),-p err(priority),--since "1 hour ago",-k(kernel),-b -1(previous boot),-o json(structured),_PID=1234.- rsyslog / syslog-ng still write text files in
/var/log/(syslog,messages,auth.log/secure) and forward logs to remote collectors. - logrotate rotates text logs (
/etc/logrotate.d/): size or time, compress, keep N. Usecopytruncateonly if the app can't reopen files; better, have the app reopen on SIGHUP or log to stdout and let journald or the container runtime handle it. - Kernel ring buffer:
dmesg -T/journalctl -k: OOM kills, disk errors, segfaults, network driver problems.
For modern services, log structured JSON to stdout, and let the platform (journald, Docker, Kubernetes) collect and ship it to a central system (Vol. 9). Never write unbounded log files without rotation; full disks are a classic outage.
Networking
Interfaces, addresses and routes
ip -br addr # interfaces and IPs (replaces ifconfig)
ip link show # link state, MTU
ip route # routing table; "default via 10.0.0.1 dev eth0"
ip route get 8.8.8.8 # which route and source IP a destination would use
ip neigh # ARP / neighbour table
Configuration tools vary by distribution: NetworkManager (nmcli), systemd-networkd, netplan (Ubuntu YAML front-end), /etc/network/interfaces (older Debian). Containers and Kubernetes build on virtual interfaces: veth pairs, bridges, VXLAN tunnels (chapter 80).
Sockets and ports
ss -tlnp # TCP listening sockets with owning process
ss -tanp state established # current TCP connections
ss -s # summary counts (TIME-WAIT, etc.)
Things to know:
- A server listens on
0.0.0.0:8080(all IPv4 interfaces),[::]:8080(all IPv6, often IPv4 too), or127.0.0.1:8080(loopback only, which is unreachable from outside a container!). - Listen backlog (
somaxconn, the app's backlog argument) limits queued connections awaitingaccept. - TIME_WAIT sockets are normal on the side that closes first; huge counts on clients suggest missing connection pooling.
- Ephemeral ports (
net.ipv4.ip_local_port_range) can run out for very high outbound connection rates to the same destination. - Each connection is a file descriptor, so
RLIMIT_NOFILEcaps connections.
DNS resolution
Applications resolve names via the C library (getaddrinfo), following /etc/nsswitch.conf (files dns): first /etc/hosts, then DNS servers from /etc/resolv.conf. Many systems run systemd-resolved with a local stub at 127.0.0.53 (resolvectl status). Go's pure-Go resolver reads these files itself; Java caches results according to networkaddress.cache.ttl (forever with a security manager in old JVMs; 30 s by default otherwise). In Kubernetes, resolv.conf's search domains and ndots:5 make every external lookup try several suffixes first (chapter 83).
Tools: dig example.com, dig +trace, getent hosts example.com (uses the same path as applications, unlike dig).
Firewalls
The kernel's packet filtering is netfilter. The modern interface is nftables (nft list ruleset); iptables commands still exist, often as a compatibility layer over nftables (iptables-nft). Higher-level managers: firewalld (RHEL family, zones), ufw (Ubuntu). Docker and Kubernetes (kube-proxy) write their own rules, so read them before adding yours. eBPF-based datapaths (Cilium) increasingly replace iptables for container networking.
Diagnosing network problems
| Question | Tool |
|---|---|
| Is the host reachable? | ping (ICMP may be blocked), tracepath / mtr (path and loss) |
| Is the port open? | nc -vz host 5432, curl -v telnet://host:5432 |
| What does HTTP do? | curl -v, curl -w '%{time_connect} %{time_starttransfer}\n' |
| TLS problems? | openssl s_client -connect host:443 -servername host |
| What's on the wire? | tcpdump -i any -nn port 5432 -w cap.pcap, then Wireshark |
| Retransmits, drops? | ss -ti (per-socket retransmits, RTT), nstat -az, ip -s link |
| MTU issues? | ping -M do -s 1472 host; symptoms: small requests work, large ones hang |
Package management
| Family | Low-level | High-level | Format |
|---|---|---|---|
| Debian, Ubuntu | dpkg |
apt |
.deb |
| RHEL, Fedora, Rocky, Alma, Amazon Linux | rpm |
dnf (formerly yum) |
.rpm |
| Alpine | — | apk |
.apk (musl-based) |
| Arch | — | pacman |
.pkg.tar.zst |
| SUSE | rpm |
zypper |
.rpm |
Concepts:
- Repositories with signed metadata (GPG keys; never disable signature checks).
- Dependency resolution, versions and pinning (
apt-mark hold,dnf versionlock). - Security updates: unattended-upgrades (Debian/Ubuntu),
dnf-automatic; reboot or restart services after library updates (needrestart). - Universal formats for desktops: Flatpak, Snap, AppImage. Nix and Guix provide reproducible, side-by-side installs.
- Language package managers (Maven, Cargo, Go modules, pip, npm) are separate and shouldn't be mixed with system Python/Node packages: use virtualenvs or
uv, and per-project toolchains. - In containers, install with
--no-install-recommendsand clean caches in the same layer (chapter 81).
Storage
The storage stack
Devices, partitions, LVM
lsblk -f # block devices, partitions, filesystems, mount points
blkid # UUIDs and types
df -hT # usage per filesystem; df -i for inodes
du -sh /var/lib/* | sort -h # what's using space
- Partitions (GPT):
parted,fdisk. - LVM layers physical volumes → volume groups → logical volumes, allowing resizing and snapshots:
pvcreate,vgcreate,lvcreate -L 50G -n data vg0,lvextend -r -L +20G vg0/data(-rgrows the filesystem too). - RAID:
mdadmsoftware RAID; or hardware RAID; or filesystem-level (Btrfs, ZFS). - Encryption: LUKS /
dm-crypt(cryptsetup). - Cloud block storage (EBS, Persistent Disk) appears as ordinary block devices (
/dev/nvme1n1).
Filesystems
| Filesystem | Notes |
|---|---|
| ext4 | Default on Debian/Ubuntu; mature, journaled; good general choice |
| XFS | Default on RHEL family; excellent for large files and parallel I/O; can grow, can't shrink |
| Btrfs | Copy-on-write, snapshots, checksums, compression, subvolumes; default on Fedora desktop and SUSE |
| ZFS | Pooled storage, checksums, snapshots, send/receive; out-of-tree on Linux for licensing reasons |
| tmpfs | In RAM (and swap); /tmp, /run, /dev/shm |
| overlayfs | Union filesystem layering read-only lower dirs under a writable upper dir: container image layers (chapter 80) |
| NFS, CIFS/SMB, FUSE | Network and user-space filesystems; mind locking and consistency semantics |
The page cache and durability
Linux uses free RAM to cache file data (the page cache). That's why free -h shows little "free" memory but lots of "buff/cache" and "available": cache is reclaimed on demand. Reads hit the cache when hot; writes land in the cache as dirty pages and are flushed later by writeback.
So write() returning success doesn't mean the data is on disk. A power loss before writeback loses it. For durability:
fsync(fd): flush the file's data and metadata to stable storage;fdatasyncskips non-essential metadata.- After creating or renaming a file, fsync the directory so the new entry is durable.
O_DIRECTbypasses the page cache (databases that manage their own caching);O_SYNC/O_DSYNCmake each write synchronous.- Databases rely on this ordering (WAL then data, Vol. 4 ch. 58); disabling fsync for speed risks corruption.
// Go: durable atomic file replace (write temp → fsync → rename → fsync dir)
func writeFileAtomic(path string, data []byte) error {
dir := filepath.Dir(path)
f, err := os.CreateTemp(dir, ".tmp-*")
if err != nil { return err }
defer os.Remove(f.Name()) // no-op after successful rename
if _, err := f.Write(data); err != nil { f.Close(); return err }
if err := f.Sync(); err != nil { f.Close(); return err } // fsync file
if err := f.Close(); err != nil { return err }
if err := os.Rename(f.Name(), path); err != nil { return err }
d, err := os.Open(dir)
if err != nil { return err }
defer d.Close()
return d.Sync() // fsync directory entry
}
// Java: FileChannel.force(true) is fsync; ATOMIC_MOVE maps to rename(2)
Path tmp = Files.createTempFile(target.getParent(), ".tmp-", "");
try (FileChannel ch = FileChannel.open(tmp, StandardOpenOption.WRITE)) {
ch.write(ByteBuffer.wrap(data));
ch.force(true);
}
Files.move(tmp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
try (FileChannel dir = FileChannel.open(target.getParent(), StandardOpenOption.READ)) { dir.force(true); }
// Rust: same pattern with std
use std::{fs::{self, File}, io::Write, path::Path};
fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
let dir = path.parent().unwrap();
let tmp = dir.join(".tmp-write");
let mut f = File::create(&tmp)?;
f.write_all(data)?;
f.sync_all()?; // fsync
fs::rename(&tmp, path)?; // atomic replace
File::open(dir)?.sync_all() // fsync the directory
}
# Python: os.fsync and os.replace
import os, tempfile
def write_atomic(path: str, data: bytes) -> None:
d = os.path.dirname(path) or "."
fd, tmp = tempfile.mkstemp(dir=d, prefix=".tmp-")
try:
with os.fdopen(fd, "wb") as f:
f.write(data); f.flush(); os.fsync(f.fileno())
os.replace(tmp, path)
dfd = os.open(d, os.O_RDONLY)
try: os.fsync(dfd)
finally: os.close(dfd)
except BaseException:
if os.path.exists(tmp): os.unlink(tmp)
raise
CPU, memory and I/O diagnostics
A method: USE
Brendan Gregg's USE method: for every resource (CPU, memory, disk, network, file descriptors), check Utilisation (how busy), Saturation (queued work it can't serve yet), and Errors. It turns "the server is slow" into a checklist instead of guesswork.
| Resource | Utilisation | Saturation | Errors |
|---|---|---|---|
| CPU | mpstat -P ALL 1, top %us/%sy |
Load average vs cores, run queue (vmstat r), cgroup throttling |
— |
| Memory | free -h (available), /proc/meminfo |
Swapping (vmstat si/so), PSI memory, reclaim |
OOM kills in dmesg |
| Disk | iostat -xz 1 %util |
aqu-sz, await |
dmesg, SMART (smartctl) |
| Network | sar -n DEV 1, ip -s link |
Socket backlog drops, retransmits | Interface errors/drops |
The famous "first 60 seconds" checklist (Netflix):
uptime # load averages (1, 5, 15 min)
dmesg -T | tail # OOM kills, I/O errors
vmstat 1 # r (run queue), free, si/so (swap), us/sy/wa/st CPU
mpstat -P ALL 1 # per-CPU balance (one hot core = single-threaded bottleneck)
pidstat 1 # per-process CPU
iostat -xz 1 # per-disk utilisation, latency
free -m # memory
sar -n DEV 1 # network throughput
sar -n TCP,ETCP 1 # connections, retransmits
top # overview
CPU
- Load average counts tasks running, runnable and in uninterruptible (D) sleep: on Linux, a high load with idle CPUs often means I/O waits, not CPU pressure. Compare against the number of cores.
- CPU time categories: us (user), sy (kernel), wa (idle waiting on I/O), st (steal: the hypervisor gave your vCPU to someone else), si/hi (interrupts).
- cgroup throttling: in containers, check
/sys/fs/cgroup/<path>/cpu.stat(nr_throttled,throttled_usec); a pod at 30% average CPU can still be throttled during bursts if its limit is low (chapter 83). - PSI (pressure stall information:
/proc/pressure/cpu|memory|io) reports the share of time tasks were stalled waiting for a resource: a direct saturation metric. - Profilers:
perf top,perf record -g+ flame graphs; language-aware profilers: async-profiler and JFR (Java), pprof (Go),cargo flamegraph/perf(Rust, C, C++, Zig), py-spy (Python). eBPF tools (bcc,bpftrace) trace kernel and user events with low overhead.
Memory
free -h: watch available, not free.- Process memory: RSS (resident in RAM, includes shared pages), PSS (proportional share), VSZ (virtual reserved, often huge and meaningless: Go and Java reserve large ranges).
smem,/proc/<pid>/smaps_rollup,pmap -x. - Swap makes memory pressure slow rather than fatal; many server and Kubernetes setups disable it (Kubernetes supports swap on cgroup v2 nodes since 1.28, with limited, opt-in behaviour).
- The OOM killer: when the kernel (or a cgroup) runs out of memory, it kills the process with the highest
oom_score(/proc/<pid>/oom_score, adjust withoom_score_adj). It appears indmesgas "Out of memory: Killed process 1234 (java)". In containers, exit code 137 (128 + SIGKILL 9) usually means an OOM kill. - Language runtimes and memory limits:
- JVM: container-aware since JDK 10 and 8u191; heap defaults to 25% of the container limit, so set
-XX:MaxRAMPercentage=75and remember non-heap memory (metaspace, thread stacks, direct buffers, code cache). - Go: set
GOMEMLIMIT(soft limit, Go 1.19+) to about 90% of the container limit so the GC works harder before the OOM killer acts. Go 1.25 also madeGOMAXPROCSrespect cgroup CPU limits by default. - Node.js:
--max-old-space-size, though recent versions read cgroup limits. - Python: no heap cap; watch RSS and worker counts (each Gunicorn worker is a process).
- Rust, C, C++, Zig: allocator choice (jemalloc, mimalloc) affects fragmentation and RSS return to the OS.
Disk I/O
iostat -xz 1:r/s,w/s,rkB/s,wkB/s,r_await/w_await(ms per I/O including queueing),aqu-sz(queue depth),%util(misleading for SSDs and NVMe, which serve many I/Os in parallel).iotop/pidstat -d 1: which processes do I/O.- Cloud disks have IOPS and throughput limits (gp3 baseline 3,000 IOPS and 125 MB/s, for example); hitting them looks like rising await.
Tracing
strace -f -tt -T -p <pid>: system calls with timestamps and durations (high overhead; fine for short diagnosis).ltrace: library calls.- eBPF / bpftrace:
opensnoop,execsnoop,biolatency,tcpretrans,runqlat,offcputime: production-safe, low-overhead tracing of kernel events. - Core dumps:
coredumpctl list,coredumpctl gdb <pid>. - Language tools:
jcmd <pid> Thread.print,jcmd <pid> GC.heap_info, JFR (Java);GOTRACEBACK=all,net/http/pprof(Go);py-spy dump --pid(Python).
Lab: the kernel under your service
Ubuntu 24.04, kernel 6.18, 2 vCPUs, 8 GB RAM, a virtio disk. Run as root (dropping caches and changing limits need it).
Experiment 1: the page cache
A 1 GB file, read after echo 3 > /proc/sys/vm/drop_caches, then again:
cold read of 1 GB: 0.596 s
warm read of 1 GB: 0.158 s
The second read came from RAM: Linux keeps recently used file data in the page cache, using memory nobody else needs. That's why free shows little "free" memory on a healthy server while "available" stays high, and why a database's second run of a query is faster. It's also why a container's memory usage includes cache it can't necessarily give back instantly (chapter 80).
Experiment 2: what durability costs
1,000 writes of 4 KB:
buffered (page cache): 0.007 s
O_DSYNC, each write must reach the disk: 0.316 s
A normal write() returns once the data is in the page cache; the kernel writes it to disk later. Forcing each write to reach the device (O_DSYNC, or fsync() after each write) was 45× slower here, about 0.3 ms per write on this virtual disk (several milliseconds on cloud network disks, under 0.1 ms on local NVMe with power-loss protection). Databases and message brokers pay this on every commit (Volume 4, chapter 72's etcd fsync); if your application writes important files, it must call fsync on them (and on the directory after a rename) or a power cut can lose them.
Experiment 3: running out of file descriptors
open-files limit: soft 20000, hard 20000
with the soft limit lowered to 256: opened 253 sockets, then: [Errno 24] Too many open files
Every socket and file uses a descriptor, and each process has a limit (ulimit -n, LimitNOFILE= in a systemd unit, --ulimit nofile= in Docker). A busy server with keep-alive connections, database pools and log files hits a low limit (1,024 is still a common default) with EMFILE errors that look like random connection failures. Check a live process with cat /proc/PID/limits and ls /proc/PID/fd | wc -l.
Experiment 4: load average isn't CPU usage
Four busy loops on two CPUs for 65 seconds:
4 busy loops on 2 CPUs for 65 s → load average: 3.17 1.58 0.80
Load average counts tasks that are running or waiting to run (and, on Linux, tasks in uninterruptible I/O sleep), averaged over 1, 5 and 15 minutes with exponential decay; the 1-minute figure was still climbing towards 4. With 2 CPUs, a load of 4 means as much work again was waiting as was running. Compare load with the CPU count, and look at vmstat 1 (the r and b columns), mpstat and pressure stall information (/proc/pressure/cpu, io, memory) to see whether CPUs, disks or memory are the bottleneck.
Experiment 5: the OOM killer
A shell in a container limited to 64 MB tries to hold 200 MB:
allocating
exit code: 137
OOMKilled=true ExitCode=137
Exit code 137 is 128 + 9: the process was killed with SIGKILL, here by the kernel's out-of-memory killer acting inside the container's memory cgroup. It got no chance to log anything. In Kubernetes this appears as OOMKilled in kubectl describe pod; on a host, in dmesg/journalctl -k. JVMs, Node and Python must be told about container limits (-XX:MaxRAMPercentage, --max-old-space-size), or they size their heaps for the whole machine (chapter 80).
Experiment 6: TIME_WAIT
500 HTTP requests, each on a new connection:
sockets in TIME_WAIT went from 95 to 595
The side that closes a TCP connection first keeps it in TIME_WAIT for 60 seconds on Linux, so delayed packets from the old connection can't corrupt a new one with the same addresses and ports. Clients making many short-lived connections can exhaust ephemeral ports (around 28,000 by default per destination). The fix is connection reuse: HTTP keep-alive, connection pools, HTTP/2, not kernel tweaks.
Try it yourself
- Run
vmstat 1during experiment 4 and during experiment 1's cold read. Which columns move? - Write a systemd unit for
tiffinwithUser=,LimitNOFILE=,MemoryMax=,Restart=on-failureandProtectSystem=strict, and check it withsystemd-analyze security. - Fill a filesystem to 100% and observe which services fail and how. Then find the culprit with
du -xh --max-depth=1 / | sort -h. - Use
strace -f -e trace=network,file ./tiffinand match its system calls to the file descriptors in/proc.
Revision sheet: Linux
Key ideas
- Shape: kernel, init (systemd), userland; the filesystem hierarchy (
/etc,/var,/usr,/proc,/sys,/run,/tmp). - Permissions: users, groups, mode bits, setuid/setgid/sticky, umask, ACLs, capabilities, root and sudo, SELinux/AppArmor.
- Processes: fork/exec, PIDs and parents, states (R, S, D, Z, T), signals, exit codes (128 + signal), zombies and reaping, nice and priorities.
- systemd: units, services (
Type=,Restart=,User=, limits, sandboxing directives), timers, targets,journalctl. - Environment: variables, shells, PATH, config files and secrets handling.
- Logs: journald, syslog, log rotation, structured logs to stdout for containers.
- Networking: interfaces, routes, DNS (
/etc/resolv.conf), ports and sockets,ss,ip,curl,dig,tcpdump, firewalls (nftables/iptables), TCP states. - Packages: apt/dnf, repositories, pinning, unattended upgrades.
- Storage: block devices, partitions, filesystems (ext4, XFS), mounts and fstab, LVM, page cache, fsync, inodes.
- Diagnostics:
top,vmstat,iostat,mpstat,pidstat, PSI,strace,perf, eBPF tools (bcc, bpftrace), the USE method.
Numbers to remember
- Exit 137 = SIGKILL (often OOM); 143 = SIGTERM.
- TIME_WAIT lasts 60 s on Linux; default ephemeral range ~28k ports.
- Lab: page cache made a 1 GB read 3.8× faster; O_DSYNC writes 45× slower than buffered; fd exhaustion at the soft limit; load 3.2 and rising with 4 busy loops on 2 CPUs.
Pitfalls
- Services running as root.
- Low
nofilelimits on busy servers. - Reading "free" memory instead of "available".
- Assuming
write()means durable. - Logs filling the disk without rotation.
- Ignoring SIGTERM, so every restart drops requests.
Glossary
- inode: a file's metadata record; directories map names to inodes.
- Page cache: kernel RAM cache of file contents.
- Load average: running + runnable (+ uninterruptible) tasks, averaged.
- PSI: pressure stall information, time tasks wait for CPU, memory or I/O.
- Capability: a slice of root's power (e.g.
CAP_NET_BIND_SERVICE). - Unit: a systemd-managed object (service, timer, socket, mount…).