Linux for Developers: Processes, Users & Permissions, Filesystems, Packages, systemd, Monitoring
"Starting with Linux 2.2, Linux divides the privileges traditionally associated with superuser into distinct units, known as capabilities, which can be independently enabled and disabled." — Linux manual pages,
capabilities(7)
Summary: Linux is one kernel plus a userland chosen by a distribution; almost every production symptom (a service that will not stop, "permission denied" on a file that looks readable, "No space left on device" with free blocks, a process that vanishes with exit code 137) is the same handful of kernel objects (processes, signals, users and modes, inodes and mounts, cgroups, memory) seen from outside, and systemd is the supervisor that turns a binary into a service. Focus: Kernel vs userland and the distribution families (Debian/Ubuntu with apt, RHEL/Fedora with dnf, Alpine with apk); processes (PID, parent/child, fork and exec, states, zombies, signals, SIGTERM vs SIGKILL, SIGHUP, exit codes, nice, /proc, ps, top, htop); users and groups, UID/GID, root and sudo; file permissions (rwx, octal modes, umask, setuid, setgid, sticky bit, ACLs, capabilities); the Filesystem Hierarchy Standard; mounts, fstab, ext4 vs xfs vs btrfs, LVM, swap, inodes, links, df/du/lsblk; systemd (units, services, targets, systemctl, timers vs cron, environment files, hardening, journalctl); logs (journald, rsyslog, logrotate); memory, the OOM killer, oom_score_adj, load average, CPU steal, iostat/vmstat/sar; network basics (ip, ss, dig); SSH keys, client config and sshd hardening; ulimit, limits.conf and file descriptors; time (chrony), locales and timezones; and the three deployments a Go or Laravel developer actually does: a Go binary as a systemd service under its own user, a PHP-FPM pool as a systemd unit, and the Laravel scheduler as a systemd timer. Learning goal: Deploy a Go binary and a Laravel app on a plain Linux server without a container, supervise them with systemd under least privilege, and, when something breaks, pick the right first command (systemctl status, journalctl -u, ps, ss, df -i, free, dmesg) and read what it says.
This chapter is the first in the Linux & Tooling group. Shell syntax, pipes, grep/sed/awk/jq and safe scripts are Shell Scripting & Text Processing; strace, perf, eBPF, gdb and core dumps (what to do after the first command fails to explain a problem) are Linux Debugging; namespaces, cgroups v2 and OverlayFS as kernel features, which are what a container is, are Containers Under the Hood; Nginx, Caddy and Apache in front of PHP-FPM or a Go service are Web Servers & Reverse Proxies in Practice. The network itself (addressing, DNS, ports and sockets, firewalls, SSH tunnels, troubleshooting) belongs to the networking chapters (IP Addressing, DNS Resolution, Ports, Sockets & Connections, Firewalls, VPNs & Tunnels, Network Troubleshooting Playbook); here only the three commands you type first are covered. The Go side of signals and graceful shutdown is OS Processes, Signals & Graceful Shutdown and of configuration and logging is CLI Flags, Environment Variables & Logging; the concepts of logs, metrics and traces are Observability.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why one kernel, many systems, and why a process model | Why it exists |
| The Unix model, Linux, systemd 2010, cgroup v2 and today's releases | Where it comes from |
| Kernel vs userland, distributions, Debian/Ubuntu vs RHEL/Fedora vs Alpine | Kernel, userland, distributions |
| Package managers: apt, dnf, apk; repositories, signatures, pinning | Package managers |
| Processes, PID, parent/child, fork and exec | Processes |
| Process states, zombies, orphans | Process states |
| Signals, SIGTERM vs SIGKILL, SIGHUP, exit codes (137, 143) | Signals and exit codes |
Nice and priorities, /proc, ps, top, htop | Priorities and inspection |
| Users and groups, UID GID, root and sudo, service users | Users and groups |
| File permissions, rwx, octal modes, umask, ownership | Permissions |
| setuid setgid sticky bit, ACLs, capabilities | Special bits, ACLs, capabilities |
Filesystem hierarchy standard: /etc /var /usr /opt /tmp | The hierarchy |
mount, fstab, ext4 vs xfs vs btrfs, LVM, swap | Mounts, filesystems, LVM, swap |
| Inodes, hard and symbolic links, disk usage (df du, lsblk) | Inodes, links, disk usage |
systemd, units, services, targets, systemctl | systemd |
| Writing a unit, environment files, hardening, limits | Writing a service unit |
| Timers vs cron | Timers |
Logs, rsyslog and journald, journalctl, log rotation with logrotate | Logs |
Memory, free, the OOM killer, oom_score_adj | Memory and the OOM killer |
| Load average, CPU steal, iostat vmstat sar, PSI | CPU, load, I/O |
| Network basics (ip, ss, dig) link to the networking chapters | Network basics |
SSH keys and config (~/.ssh/config), sshd hardening basics | SSH |
| ulimit and limits.conf, file descriptors | Limits |
| Time and NTP, chrony, locales and timezones | Time, locales |
| Build graph of a boot, errors you will see, knobs | Mechanics |
| Service user for a Go binary; deploying a Go binary as a systemd service | Go |
| PHP-FPM pool as a systemd unit; Laravel scheduler as a systemd timer; queue workers | Laravel |
| Nine classic problems and their fixes | Solving the classic problems |
| Which distribution, filesystem, scheduler, log path | Choosing |
| One VM to a fleet | In architecture |
| Commands with expected output | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The objects you meet, and the command that shows each one.
| Object | What it is | First command to look at it |
|---|---|---|
| Process | A running program with a PID, a parent, a user, open files, an environment and memory | ps -eo pid,ppid,user,stat,etime,cmd, ls -l /proc/<pid>/ |
| Signal | A small integer message to a process; most can be caught, SIGKILL and SIGSTOP cannot | kill -l, kill -TERM <pid>, strace -e signal |
| User, group | Numbers (UID, GID) that the kernel checks; names are a lookup in /etc/passwd | id, getent passwd orders |
| File mode | Nine permission bits (owner, group, other) plus setuid, setgid, sticky | ls -l, stat -c '%a %U:%G %n' file |
| Inode | The record with owner, mode, size, timestamps and block pointers; names point to it | ls -i, stat, df -i |
| Mount | A filesystem attached at a directory; /etc/fstab lists the permanent ones | findmnt, lsblk -f, df -hT |
| Unit | A thing systemd manages: service, timer, socket, target, mount, path | systemctl list-units, systemctl cat orders-api |
| cgroup | A tree of process groups with resource limits and accounting; one per service | systemd-cgls, systemctl status, /sys/fs/cgroup/ |
| Journal | systemd's structured log store, indexed by unit, priority, boot, time | journalctl -u orders-api -f |
| Memory | Anonymous pages, page cache, swap; the OOM killer is the last resort | free -h, cat /proc/meminfo, dmesg |
| Socket | An endpoint a process listens on or connects with | ss -ltnp, ss -s |
| Clock | System time kept right by chrony; timezone is presentation | timedatectl, chronyc tracking |
The distribution families.
| Family | Package format and tool | Typical use | Release rhythm (from the vendors' pages, 2026-11-29) | Service manager, libc |
|---|---|---|---|---|
| Debian | .deb, apt, dpkg | Stable servers, base of many images | Debian 13 "trixie" released 9 August 2025 | systemd, glibc |
| Ubuntu | .deb, apt, snap | Cloud VMs, developer laptops, LTS servers | LTS every two years (24.04 LTS, 26.04 LTS on Canonical's page) | systemd, glibc |
| RHEL, Rocky, Alma, CentOS Stream | .rpm, dnf, rpm | Enterprise, regulated environments | Major releases with multi-year support (Red Hat lifecycle page) | systemd, glibc, SELinux enforcing |
| Fedora | .rpm, dnf | Developer workstation, upstream of RHEL | New release about every six months, "approximately 13 months" of updates | systemd, glibc, SELinux enforcing |
| Alpine | .apk, apk | Small container base images, routers | A branch each May and November; main repository "typically supported for 2 years" | OpenRC by default, musl, BusyBox |
What to do first when something is wrong.
| Symptom | First command | What you are checking |
|---|---|---|
| Service will not start | systemctl status orders-api, then journalctl -u orders-api -n 50 --no-pager | Exit status, the last log lines, restart counter |
| "Permission denied" | namei -l /path/to/file, id | Every directory in the path needs x for your class |
| "No space left on device" | df -h then df -i then lsof +L1 | Blocks, inodes, deleted-but-open files |
| Process gone, exit 137 | dmesg -T, journalctl -k, systemctl status | OOM killer or a cgroup limit |
| Everything slow | uptime, vmstat 1 5, iostat -xz 1 3, free -m | Load, run queue, swap, disk wait, steal |
| "Connection refused" | ss -ltnp, curl -v | Is anything listening, on which address |
| Wrong time in logs | timedatectl, chronyc tracking | Synchronised? Which timezone? |
| Cron job did not run | systemctl list-timers, journalctl -u <unit> | Last and next trigger, exit status |
Why it exists
An operating system kernel has four jobs that every program would otherwise do for itself and do badly: share the CPU between programs, give each a private view of memory, hide the differences between disks and network cards behind files and sockets, and decide who may do what. Unix answered with a small set of ideas that Linux still follows: a process is the unit of execution and isolation, a file (or something that looks like one) is the interface to almost everything, users and permissions are numbers the kernel checks on every call, and a program is started by an existing one (fork then exec) rather than by a magic launcher.
Everything on a Linux server is a consequence of those ideas. The reason kill takes a number, the reason /proc looks like a directory of text files, the reason a daemon must not run as root, and the reason systemd can put every service in its own cgroup and stop it with one command are the same reason: the system is small and uniform.
| Trade-off | What you get | What it costs |
|---|---|---|
| Everything is a file or a process | One vocabulary (open, read, kill) for devices, sockets, kernel state | Names hide very different things; /proc/meminfo is not a file on disk |
| Discretionary permissions (owner decides) | Simple, fast, predictable | Easy to over-grant; a compromised owner account has everything that owner has |
| One kernel, many distributions | Choice of package manager, release rhythm, libc | The same command can behave differently on Debian and Alpine (glibc vs musl, GNU vs BusyBox tools) |
| systemd as one supervisor for services, timers, sockets, mounts, logging | Uniform units, dependencies, cgroup limits, sandboxing | A large surface to learn; some distributions (Alpine) choose a different init |
| Overcommit and the page cache | Fast, efficient use of RAM | "Free" memory looks small, and when memory really runs out the kernel kills a process |
Text configuration under /etc | Diff-able, version-controlled, automatable | No schema; a typo is found at reload time |
An analogy. A Linux server is a building with a caretaker. Each tenant (process) has a flat with its own key (UID) and a door rule (mode bits); the caretaker (the kernel) decides who may enter which room, how much electricity (CPU) and water (memory) each flat may use, and, when the building is out of water, evicts a tenant. systemd is the building manager: it knows which tenants must be present at opening time (targets), starts them in order, restarts the ones that collapse, and keeps a log book (the journal) for each.
Three common misunderstandings, up front
- "Linux is an operating system." Linux is the kernel. What you log into (a shell,
ls,apt, systemd, glibc) is userland, supplied by a distribution. Alpine and Ubuntu run the same kernel family with almost no userland in common. - "Free memory is the number under
free." On Linux unused RAM is wasted RAM; the kernel fills it with file cache and gives it back on demand. The number to watch isavailable. - "Killing a process makes it stop." A process stops when it chooses to, on SIGTERM; SIGKILL cannot be caught and skips cleanup, and a process in uninterruptible disk wait ("D" state) does not die until the I/O returns. A killed child also remains in the process table as a zombie until its parent collects its exit status.
Where it comes from
| When | What happened | Source |
|---|---|---|
| Unix origins | The model this chapter describes: processes created by fork and execve, users and group IDs, permission bits | fork(2), execve(2), credentials(7) document today's form |
| 1988-1990 | POSIX.1 standardises the Unix interface that Linux later implements ("P1990" in the signal table of signal(7) means POSIX.1-1990) | signal(7) |
| Linux | The kernel is by Linus Torvalds "with assistance from a loosely-knit team of hackers"; distributions combine it with a userland | kernel.org about page |
| 1993 | A three-line change makes Linux load averages include uninterruptible tasks, so the number reflects disk demand too | Brendan Gregg, "Linux Load Averages: Solving the Mystery" |
| Linux 2.2 (1999) | Superuser privilege split into capabilities | capabilities(7) |
| April 2010 | Lennart Poettering announces systemd, built on socket activation as the "core change" | LWN, "The road forward for systemd", 26 May 2010 |
| 2016 onwards | cgroup v2, a single unified hierarchy ("cgroup v2 has only single hierarchy"), replaces v1; systemd and container runtimes move to it | kernel cgroup-v2 documentation |
| 9 August 2025 | Debian 13 "trixie" stable; point release 13.8 on 21 November 2026 | debian.org releases page |
| June 2026 | Alpine 3.24 released, supported until 2028-06-01 | alpinelinux.org releases page |
| 2026 | Ubuntu 26.04 LTS is the current LTS on Canonical's release-cycle page | ubuntu.com release cycle |
The history explains the layout of this chapter. Processes, files and users are the Unix core and have barely changed; capabilities, cgroups and namespaces are the Linux additions that made containers possible; systemd replaced a pile of init shell scripts with declarative units, which is why a modern service is described by a file and not by a script. Distributions differ in what they put around the kernel, not in what the kernel does.
The concept catalogue
Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each distribution or tool does, and the fix. Command output in the sequences is the typical shape on a Debian or Ubuntu server; nothing in this catalogue claims to be a captured run (the Lab says which commands were run on the build host and which were not).
Kernel, userland, distributions: Debian/Ubuntu vs RHEL/Fedora vs Alpine Must-know
In plain words: The kernel is the one program that talks to the hardware and enforces the rules; everything you type into (shell, ls, apt, systemd, the C library) is userland, and a distribution is somebody's chosen bundle of kernel plus userland plus a way to update it.
Common misunderstanding: "My container runs Ubuntu, so it has Ubuntu's kernel." A container shares the host's kernel and brings only userland. uname -r inside any container prints the host's kernel version; only /etc/os-release tells you which userland you have.
Definition: The kernel exposes system calls (fork, open, read, mount, kill); the C library (glibc on Debian, Ubuntu, RHEL and Fedora; musl on Alpine) wraps them for programs; /etc/os-release identifies the distribution in a machine-readable format (ID=, VERSION_ID=, ID_LIKE=). A distribution defines the package format, the repositories, the release and support schedule, the default init system and the default security framework.
what a command touches, from your keyboard to the hardware
1 bash reads "ls -l /srv" userland (shell)
2 bash calls fork(), the child calls execve("/usr/bin/ls") userland -> kernel
3 ls (linked against glibc or musl) calls openat(), getdents64(), statx()
4 the kernel checks permissions (UID/GID/mode), reads the inode, returns bytes
5 ls formats and write()s to the terminal; the kernel moves bytes to the ptyReal scenarios:
- A binary built on Ubuntu 26.04 fails on an older RHEL with a "version
GLIBC_x.ynot found" loader error: a binary needs at least the glibc version it was linked against, which is why a static Go binary (CGO_ENABLED=0) is the easy way to ship one artefact to every family. - A shell script written on Ubuntu fails on Alpine because
/bin/shis BusyBoxashand there is nobash; the same script passes on Debian where/bin/shisdash. Write#!/bin/shscripts to POSIX or installbashdeliberately. - A kernel feature (
io_uring, cgroup v2,userfaultfd) is available inside a container only if the host kernel has it; "works in Docker on my laptop" can differ on a cloud VM image. - A team standardises on one distribution for servers and a different one (Alpine, distroless) for container images; the kernel is the host's, the userland is the image's.
| Distribution | Package tool | C library and init | Notes (sourced where quoted) |
|---|---|---|---|
| Debian stable | apt, dpkg | glibc, systemd | Debian 13 "trixie" released 9 August 2025 (debian.org); common server and container base |
| Ubuntu LTS | apt, snap | glibc, systemd | Debian-based; LTS releases 24.04 and 26.04 on Canonical's page; AppArmor is "installed and loaded by default" (Ubuntu server docs) |
| RHEL / Rocky / Alma / CentOS Stream | dnf, rpm | glibc, systemd | On RHEL "Enforcing mode is the default, and recommended, mode of operation" for SELinux (Red Hat docs) |
| Fedora | dnf | glibc, systemd | New release about every six months, updates for "approximately 13 months" (Fedora docs); upstream of RHEL |
| Alpine | apk | musl, BusyBox | "a security-oriented, lightweight Linux distribution based on musl libc and busybox" (alpinelinux.org); no systemd in the base set, so units do not apply |
Fix / how to use it: read /etc/os-release and uname -r first; install by the distribution's tool, never by copying binaries into /usr; for a Go service compile with CGO_ENABLED=0 so the distribution does not matter; for PHP use the distribution's php-fpm package or a vendor repository and pin the version you tested.
Package managers: apt, dnf, apk Must-know
In plain words: A package manager downloads signed archives from a repository, resolves what each one needs, unpacks files into the right places and remembers what it installed so it can remove or upgrade it cleanly.
Common misunderstanding: "apt update upgrades my packages." It only refreshes the list of what is available. apt upgrade (or dnf upgrade, apk upgrade) installs the new versions. In a Dockerfile, an update in its own cached layer then installing from a stale list is the classic bug; the images chapter covers it.
Definition: The low-level tool installs one file (dpkg -i x.deb, rpm -i x.rpm); the high-level tool talks to repositories, resolves dependencies and checks signatures. Debian's apt-get documentation states that autoremove "is used to remove packages that were automatically installed to satisfy dependencies for other packages and are now no longer needed". Alpine's wiki explains that apk add foo and apk del bar "manipulate the desired state by adding or removing packages foo, bar respectively as a dependency constraint in /etc/apk/world".
| Task | Debian, Ubuntu | RHEL, Fedora | Alpine |
|---|---|---|---|
| Refresh the index | apt update | dnf makecache (done automatically) | apk update |
| Install | apt install nginx | dnf install nginx | apk add nginx |
| Upgrade everything | apt upgrade | dnf upgrade | apk upgrade |
| Remove, and unused dependencies | apt remove x, apt autoremove | dnf remove x | apk del x |
| Which package owns a file | dpkg -S /usr/bin/ls | rpm -qf /usr/bin/ls | apk info -W /usr/bin/ls |
| Files in a package | dpkg -L nginx | rpm -ql nginx | apk info -L nginx |
| Search | apt search, apt-cache policy x | dnf search, dnf info x | apk search x |
| Repositories | /etc/apt/sources.list.d/*.sources | /etc/yum.repos.d/*.repo | /etc/apk/repositories |
| Hold a version | apt-mark hold x | dnf versionlock add x (plugin) | apk add 'x=1.2.3-r0' pin in world |
| Unattended security updates | unattended-upgrades | dnf-automatic | cron plus apk upgrade (no standard tool) |
apt install nginx (Debian), in order
1 read /etc/apt/sources.list.d/*.sources; local index in /var/lib/apt/lists (from the last apt update)
2 resolve nginx and its dependencies against the index (candidate version = highest priority)
3 download .deb files from the mirror into /var/cache/apt/archives; verify the signed Release metadata
4 dpkg unpacks files, runs the package's preinst/postinst scripts (creates users, enables units)
5 record the package in /var/lib/dpkg/status; "manually installed" marks decide what autoremove may dropReal scenarios:
- A server is missing a patch released a month ago because
apt updatewas never scheduled;unattended-upgradeshandles security-only updates automatically. - A Laravel deployment needs PHP 8.4 and the distribution ships 8.3: add the vendor repository (with its signing key in
/etc/apt/keyrings), not a random.deb. - Two services need different versions of a library: containers or static linking, not parallel installs in
/usr. - An image build pulls
curland 80 MB of recommended packages:apt install --no-install-recommends.
Fix: pin the OS release in the base image or the server template, update on a schedule, install only what the service needs, keep third-party repositories to a minimum and check each one's signing key; for reproducible builds record the versions (apt list --installed, rpm -qa, apk info -v).
Processes: PID, parent/child, fork and exec Must-know
In plain words: A process is a running copy of a program. Every process has a number (PID), a parent, an owner, and its own memory and open files. New processes are made by copying an existing one and then replacing the copy's program.
Common misunderstanding: "fork starts a new program." fork only duplicates the caller; execve is what loads a different program into that process. A shell does both: it forks, the child calls exec on ls, and the shell waits.
Definition: fork(2): "The child process is an exact duplicate of the parent process except for the following points: The child has its own unique process ID ..." execve(2) replaces the current program; the PID, the parent, the open file descriptors (without close-on-exec), the user and the environment (unless replaced) remain. The kernel keeps the parent link (PPID); PID 1 (init, systemd) is the ancestor of everything and adopts orphans.
$ sh -c 'sleep 60 &' # one shell, one child that outlives it
1 shell (PID 1200) calls fork() -> child PID 4821, same code, same fds
2 child calls execve("/bin/sleep", ["sleep","60"], env) -> same PID 4821, new program
3 shell exits; the kernel re-parents PID 4821 to PID 1 (or a subreaper)
4 after 60 s sleep calls exit(0); PID 1 calls wait() and the entry disappears
ps -o pid,ppid,stat,cmd -p 4821 -> "4821 1 S sleep 60" (PPID is now 1)Real scenarios:
systemctl stop orders-apiworks because systemd started the process, knows its PID and its cgroup, and can signal the whole group.- A PHP-FPM master forks workers; killing a worker's PID does nothing lasting (the master forks a replacement), killing the master stops the pool.
- A shell script that starts
./server &and exits leaves the server running as a child of PID 1, with no supervision and no log capture. - A Go program using
os/execmustWait()for each child or leave zombies (see States); the repository'sexitcodepackage shows how.
| Tool | What it shows about processes |
|---|---|
ps -eo pid,ppid,user,stat,etime,rss,cmd | Snapshot with parent, owner, state, elapsed time, resident memory |
pstree -ap | The parent/child tree with PIDs and arguments |
pgrep -af orders, pkill | Find or signal by name or pattern (use -x for an exact name) |
ls -l /proc/<pid>/exe /proc/<pid>/cwd /proc/<pid>/fd | Binary, working directory, open files and sockets |
systemd-cgls | Processes grouped by unit and slice |
lsof -p <pid>, ss -ltnp | Open files and listening sockets with their process |
Fix: never identify a service by a PID you copied by hand; let the supervisor hold the PID; look at a process through /proc/<pid>/ (see Priorities and inspection). For the Go side of starting and stopping children, read OS Processes, Signals & Graceful Shutdown.
Process states, zombies and orphans Important
In plain words: A process is mostly waiting. The state letter in ps says what it waits for. A "zombie" is a process that has already died and only keeps its exit status until its parent asks for it.
Common misunderstanding: "A zombie is a hung or runaway process, and kill -9 removes it." A zombie is already dead; signals do nothing to it. It disappears when the parent calls wait(), or when the parent dies and PID 1 adopts and reaps it.
Definition: ps reports state codes: R running or runnable, S interruptible sleep (a signal wakes it), D uninterruptible sleep (usually I/O), T stopped, Z zombie. wait(2): "A child that terminates, but has not been waited for becomes a 'zombie'. The kernel maintains a minimal set of information about the zombie process (PID, termination status, resource usage information) in order to allow the parent to later perform a wait". Zombies consume only a process-table slot, but "if this table fills, it will not be possible to create further processes". An orphan is a live process whose parent died; it is re-parented to PID 1 or the nearest subreaper.
exit-status handshake
T0 child calls exit(3) state S -> Z, memory freed, PID and status kept
T1 kernel sends SIGCHLD to the parent (ignored by default)
T2 parent calls wait()/waitpid()/cmd.Wait() receives status 3
T3 kernel frees the process-table entry the PID may now be reused
if the parent never reaches T2, ps shows "Z" and "<defunct>" until the parent exitsReal scenarios:
- A long-running Go service starts
exec.Command("convert", ...)withStart()and never callsWait(): thousands of<defunct>entries accumulate and eventuallyfork: retry: Resource temporarily unavailable. - A container whose PID 1 is a shell script or an application that does not reap children accumulates zombies; the fix is an init (
docker run --init, tini) or a PID 1 that waits. - A process stuck in
Dafter an NFS server vanished ignores SIGKILL until the I/O returns or times out; load average rises because Linux countsDtasks in it. topshows2 zombie: harmless in number; a growing count means one parent is leaking.
| State | ps STAT | Cause | What to do |
|---|---|---|---|
| Running or runnable | R | On CPU or in the run queue | Look at CPU, pidstat, perf |
| Sleeping | S | Waiting for I/O, a timer, a lock, a socket | Normal; check what with cat /proc/<pid>/wchan, strace -p |
| Uninterruptible | D | Waiting on disk or a kernel lock | Check storage health; iostat -xz; do not expect kill to work |
| Stopped | T | SIGSTOP, Ctrl+Z, a debugger | kill -CONT <pid> or fg |
| Zombie | Z | Exited, parent has not waited | Fix the parent (call Wait), or restart it |
| Idle kernel thread | I | Kernel worker with nothing to do | Ignore |
Fix: every Start has a Wait; use systemd or an init as PID 1 so orphans are reaped; investigate a D state through its device, not through signals.
Signals, SIGTERM vs SIGKILL, SIGHUP, exit codes Must-know
In plain words: A signal is a tiny message sent to a process. Most signals can be caught: the program decides what to do. SIGTERM asks politely; SIGKILL cannot be refused. When a process ends, it leaves a number (the exit code) that its parent can read.
Common misunderstanding: "kill kills." The command kill sends a signal; the default is SIGTERM (15), which a program may handle, ignore or use to shut down gracefully. Only SIGKILL (9) and SIGSTOP always act, and SIGKILL gives the program no chance to flush files or release locks.
Definition: signal(7): "The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored." Common signals: SIGHUP 1 (terminal hangup; by convention a daemon re-reads configuration), SIGINT 2 (Ctrl+C), SIGQUIT 3, SIGKILL 9, SIGTERM 15, SIGUSR1/SIGUSR2 (application-defined; PHP-FPM uses SIGUSR2 for graceful reload), SIGCHLD (a child ended), SIGSTOP/SIGCONT (pause, resume), SIGPIPE (write to a closed pipe). Exit codes: 0 success, 1-255 failure by convention; a shell reports death by signal as 128 + signal, so 137 = SIGKILL (OOM killer, kill -9, cgroup limit) and 143 = SIGTERM; 126 "found but not executable", 127 "command not found", 2 usually "misuse".
what systemctl stop orders-api does (TimeoutStopSec=15, app drains for 8 s)
T0 systemd sends SIGTERM to the main process (KillMode=control-group: to the group)
T0+ the app's signal.NotifyContext fires, readiness flips off, Shutdown() waits for requests
T8 the app returns from run() and exits 0 -> unit "inactive (dead)", result "success"
or
T15 still running: systemd sends SIGKILL to every remaining process in the unit's cgroup
unit result "timeout"; exit status 137 (128+9) in the journalReal scenarios:
- A deploy script runs
kill -9on the old process "to be sure": in-flight requests are cut, a lock file stays, a half-written file remains.kill(SIGTERM) and a wait with a deadline is the right order. docker stopor Kubernetes sends SIGTERM to PID 1; if the app is started throughsh -c, the shell receives it and does not forward it, the app is killed after the grace period with 137.nohup ./app &survives a closed SSH session because it ignores SIGHUP; under systemd you do not need either.exit status 143in CI means the job was cancelled with SIGTERM, not that the program failed.
| Signal | Number | Default | Typical use in this stack |
|---|---|---|---|
| SIGTERM | 15 | Terminate | Graceful stop: systemd, Docker, Kubernetes; Go signal.NotifyContext; Laravel workers finish the job |
| SIGKILL | 9 | Terminate, uncatchable | Last resort after the stop timeout; OOM killer |
| SIGINT | 2 | Terminate | Ctrl+C in a terminal |
| SIGHUP | 1 | Terminate | Reload configuration (nginx, many Go services); terminal closed |
| SIGQUIT | 3 | Terminate and core dump | Go prints all goroutine stacks and exits; PHP-FPM graceful stop |
| SIGUSR1 | 10 (x86) | Terminate | nginx and PHP-FPM reopen logs (after logrotate) |
| SIGUSR2 | 12 (x86) | Terminate | PHP-FPM graceful reload; nginx binary upgrade |
| SIGCHLD | 17 (x86) | Ignore | A child exited; the parent should wait |
| SIGSTOP / SIGCONT | 19 / 18 (x86) | Stop / resume | Debugging, job control |
Fix: handle SIGTERM; make PID 1 forward signals (exec form, exec "$@" in scripts, an init); give TimeoutStopSec more time than the application's drain; read exit codes as 128+n before you search for a bug. The repository's exitcode package turns an *exec.ExitError into exactly this "exited with status N or killed by signal S" report.
Nice and priorities, /proc, ps, top, htop Important
In plain words: The kernel exposes its live state as a read-only directory of text files, /proc. ps, top and htop are just readers of it. "Nice" is a politeness number: a higher value gives the CPU away.
Common misunderstanding: "nice makes a process faster or slower." It only changes the weight in the CPU scheduler when there is contention; on an idle machine every niceness gets all the CPU it wants. And a nice value does nothing for disk I/O (use ionice) or memory.
Definition: nice(1): "Niceness values range from -20 (most favorable to the process) to 19 (least favorable to the process)." Only root (or CAP_SYS_NICE) may lower the number. /proc/<pid>/ holds per-process files: status (name, state, PPid, Uid, Gid, VmRSS, Threads, CapEff), cmdline, environ, fd/, maps, limits, oom_score, oom_score_adj, cgroup. System-wide: /proc/meminfo, /proc/loadavg, /proc/cpuinfo, /proc/mounts. The repository's procfs package parses these formats from any io.Reader.
reading one process with nothing but cat (Linux, illustrative)
1 cat /proc/4821/status Name: orders-api State: S (sleeping) PPid: 1 Uid: 991 991 991 991
2 ls -l /proc/4821/exe -> /opt/orders-api/releases/20261129T0912Z-ab12cd/orders-api
3 tr '\0' ' ' < /proc/4821/cmdline ; cat /proc/4821/limits | grep 'open files'
4 ls /proc/4821/fd | wc -l number of open descriptors (compare with the limit)
5 cat /proc/4821/oom_score_adj 0| Tool | Use | Key flags and keys |
|---|---|---|
ps | One snapshot | ps aux, ps -eo pid,ppid,%cpu,%mem,stat,cmd --sort=-%mem, ps -ef --forest |
top | Live view | 1 per-CPU, M sort by memory, P by CPU, c full command, H threads, k kill; -b -n 1 for scripts |
htop | Friendlier top | F5 or t tree, F6 sort, F4 filter, F9 or k signal (htop manual); a separate package |
pidstat 1 | Per-process rates | -d I/O, -r memory faults, -w context switches |
nice -n 10 cmd, renice -n 5 -p PID | Start or change niceness | Range -20..19 |
ionice -c3 cmd | Idle I/O class | Only effective with some I/O schedulers |
systemd Nice=, CPUWeight=, IOWeight= | Same through a unit | See Writing a service unit |
Real scenarios: a nightly pg_dump fights the web workers for CPU: Nice=10 and IOSchedulingClass=idle in its unit (the repository's orders-backup.service); top shows %CPU above 100 for a multi-threaded Go service (100 per core); ps shows RSS (resident memory) but not what is shared, so summing it over-counts.
Fix: use /proc and ps for facts, top for "what is busy right now", and the unit file for permanent priorities. Deep tracing is Linux Debugging.
Users and groups: UID GID, root and sudo Must-know
In plain words: The kernel knows people only as numbers. A user name is a label in /etc/passwd. Each file and each process carries a user number and a group number, and every permission check compares them.
Common misunderstanding: "sudo makes me root." sudo runs one command as another user (root by default) if /etc/sudoers allows it, and logs it. Your shell stays yours. Also "root" is not a name but UID 0; any process with UID 0 (or the right capabilities) bypasses file permission checks, whatever it is called.
Definition: credentials(7): processes have a real, an effective, a saved set-user-ID and a filesystem UID; "Saved set-user-ID and saved set-group-ID. These IDs are used in set-user-ID and set-group-ID programs to save a copy of the corresponding effective IDs that were set when the program was executed". Linux uses the filesystem IDs for file access. Accounts live in /etc/passwd (name, UID, GID, GECOS, home, shell), /etc/shadow (password hashes, root only), /etc/group. By convention UIDs below 1000 (distribution-dependent) are system accounts, 1000 and above are people. A service user is a system account with no password, no login shell (/usr/sbin/nologin) and a home that is the service's state directory.
creating the account a Go service runs as (script: provision-service-user.sh)
1 getent passwd orders || useradd --system --user-group --home-dir /var/lib/orders-api \
--no-create-home --shell /usr/sbin/nologin orders
2 install -d -m 0750 -o root -g orders /etc/orders-api (readable by the service, writable by root)
3 install -d -m 0750 -o orders -g orders /var/lib/orders-api (state the service writes)
4 id orders -> uid=991(orders) gid=991(orders) groups=991(orders)
5 ssh/su into it is impossible (nologin); the only way in is systemd's User=ordersReal scenarios:
- A deploy user (
deploy) owns/opt/orders-api/releases; the service user (orders) only reads them. A compromise of the service cannot replace its own binary. - A developer adds themself to the
dockergroup "to avoid sudo": that is root-equivalent, because Docker can mount/into a container. - A file owned by UID 1000 on an NFS share or a bind mount appears as another name on a host where UID 1000 maps differently; ownership is the number, not the name.
- A web server user (
www-dataon Debian,nginxorapacheon RHEL,www-dataornobodyon Alpine images) differs by distribution; configuration that hard-codes the name breaks on migration.
| Concern | Debian, Ubuntu | RHEL, Fedora | Alpine |
|---|---|---|---|
Admin group for sudo | sudo | wheel | wheel (with doas or sudo installed) |
| Create system user | adduser --system or useradd --system | useradd --system | adduser -S, addgroup -S (BusyBox) |
| Web server user | www-data | nginx or apache | set by the package (nginx for the nginx package) |
| Default shell for system users | /usr/sbin/nologin | /sbin/nologin | /sbin/nologin |
| Declarative users | systemd-sysusers (/etc/sysusers.d/*.conf) | same | not systemd |
Fix: one system user per service; no shared logins; sudo through a drop-in file under /etc/sudoers.d/ edited only with visudo -f; deploy keys instead of passwords; check id and getent before debugging "permission denied". The sysusers.d file in the repository (orders.sysusers) shows the declarative form: u orders - "Orders API service" /var/lib/orders-api /usr/sbin/nologin.
File permissions: rwx, octal modes, umask, ownership Must-know
In plain words: Every file has an owner, a group and nine on/off switches: read, write, execute for the owner, for the group, and for everybody else. The kernel picks one of the three sets for you and applies only that one.
Common misunderstanding: "If the group may write, then the owner may too." The owner is checked first and alone: a file with mode 0466 owned by you denies you writing even though the group and everyone else may write. Another: "x on a directory means 'run'." On a directory r lists names, x lets you enter and use names in it, and w (with x) lets you create, rename and delete entries.
Definition: The mode is a 12-bit number written in octal: permissions rwx as 4, 2, 1 for each of owner, group, other (0640 = owner read+write, group read, other nothing), plus a leading digit for setuid (4), setgid (2) and sticky (1). The umask (umask(2)) "sets the calling process's file mode creation mask (umask) to mask & 0777"; "permissions in the umask are turned off from the mode argument to open(2) and mkdir(2)", so 0666 & ~0022 = 0644 for files and 0777 & ~0022 = 0755 for directories. Ownership is changed by root only (chown), the group by the owner into one of their groups (chgrp), modes by the owner (chmod).
path walk for open("/srv/shop/storage/logs/laravel.log", O_WRONLY) as uid 33 (www-data)
1 / needs x for uid 33's class ok (drwxr-xr-x root root)
2 /srv x ok
3 /srv/shop drwxr-x--- deploy deploy -> class "other" has no x EACCES: Permission denied
(the file itself may be 0666; the directory in front of it decides first)
diagnose: namei -l /srv/shop/storage/logs/laravel.logReal scenarios:
- Laravel returns 500 because
storage/andbootstrap/cacheare not writable by the PHP-FPM user:chown -R deploy:www-datathenchmod -R g+rwX(capitalXadds execute only to directories and already-executable files), andchmod g+son directories so new files inherit the group. - A secret file with mode
0644in/etc/orders-api/: every local user can read it.0640 root:orderslets only the service read it. - A cron job creates reports under umask
0077; the web server cannot read them. SetUMask=0027in the unit and the group in the directory. chmod -R 777"fixes" a deployment and turns the application tree into a place any local process can modify.
| Mode | Symbolic | Meaning | Typical use |
|---|---|---|---|
0644 | rw-r--r-- | Owner writes, everyone reads | Config that is not secret, static files |
0600 | rw------- | Owner only | SSH private keys, .env for a login user |
0640 | rw-r----- | Owner writes, group reads | Service config readable by the service group |
0755 | rwxr-xr-x | Owner full, others read and enter | Binaries, public directories |
0750 | rwxr-x--- | Owner full, group read and enter | Service directories |
0775 | rwxrwxr-x | Group may write | Shared deploy directories (with setgid) |
1777 | rwxrwxrwt | Anyone creates, only owner deletes | /tmp |
Fix: least privilege by class; one owner (the deploy user for code, root for config, the service user for state), a group for sharing; set the umask in the unit (UMask=0027); read problems with namei -l, ls -ld on each directory, id, and never solve a permission error with 777. The repository's perms package models the check (owner class, then group, then other) and round-trips octal and symbolic forms; its test creates a real file under a real umask and compares with the model.
setuid, setgid, sticky bit, ACLs, capabilities Important
In plain words: Three extra bits and two extra systems exist for cases where nine switches are not enough: running a program with its owner's identity, sharing a directory safely, giving a named person extra access, and splitting "root" into small powers.
Common misunderstanding: "To bind port 80, a service must run as root." Binding below 1024 needs only CAP_NET_BIND_SERVICE; a systemd unit can grant just that (AmbientCapabilities=CAP_NET_BIND_SERVICE) or avoid it entirely with socket activation or a reverse proxy.
Definition:
- setuid / setgid on an executable: the program runs with the file owner's (or group's) effective ID (
chmod u+s, mode4755)./usr/bin/sudoandpasswdrely on it.lsshowss(-rwsr-xr-x); a capitalSmeans the bit is set without execute, usually a mistake. On a directory, setgid makes new files inherit the directory's group. - sticky bit on a directory: "restricted deletion flag": only the file's owner (or the directory's owner or root) may delete or rename entries. It is why
/tmpis mode1777. - POSIX ACLs (
getfacl,setfacl -m u:alice:rw file, default ACLs with-d) add named users and groups with a mask entry that caps them; the filesystem must support them (ext4, XFS and Btrfs do).ls -lshows a+after the mode. - Capabilities (
capabilities(7)): "Starting with Linux 2.2, Linux divides the privileges traditionally associated with superuser into distinct units ... Capabilities are a per-thread attribute." Examples:CAP_NET_BIND_SERVICE("Bind a socket to Internet domain privileged ports (port numbers less than 1024)"),CAP_CHOWN,CAP_DAC_OVERRIDE,CAP_SYS_ADMIN(a very broad catch-all),CAP_SYS_NICE,CAP_NET_RAW. Inspect withgetpcaps <pid>or theCapEffline in/proc/<pid>/status; theprocfspackage decodes that mask.
CapEff: 0000000000000400 (from /proc/<pid>/status, as parsed by procfs.DecodeCaps)
1 0x400 is bit 10 1 << 10
2 bit 10 in include/uapi/linux/capability.h CAP_NET_BIND_SERVICE
3 so this process may bind port 80/443 although its UID is 991
systemd equivalents: AmbientCapabilities=CAP_NET_BIND_SERVICE CapabilityBoundingSet=CAP_NET_BIND_SERVICEReal scenarios:
- A shared upload directory
drwxrwsr-x deploy www-data(setgid) keeps every new file in groupwww-datawithout any chmod afterwards. - A scan finds
-rwsr-xr-xon a helper binary nobody remembers: a privilege-escalation candidate;find / -xdev -perm -4000 -type flists all setuid files. - A backup user needs read access to
/var/lib/orders-apiwithout being in its group:setfacl -R -m u:backup:rX /var/lib/orders-api. - A Go binary run with
setcap 'cap_net_bind_service=+ep' ./orders-apibinds:443as a normal user; the capability is stored in a file extended attribute and is lost when the file is replaced by a new build, which is why the unit'sAmbientCapabilitiesis the safer place.
| Mechanism | Granularity | Where it is set | Risk |
|---|---|---|---|
| Mode bits | owner, group, other | chmod | Over-broad groups; world-writable files |
| setuid / setgid | the program's identity | chmod u+s, g+s | Privilege escalation through bugs in the program |
| Sticky bit | deletion in a shared directory | chmod +t | Forgetting it on a shared directory |
| POSIX ACLs | named users and groups | setfacl | Invisible in plain ls -l; backups and cp may drop them |
| Capabilities | one root power at a time | unit file, setcap, container runtime | Some (CAP_SYS_ADMIN) are close to full root |
| SELinux / AppArmor | labels or path profiles on top of all of the above | policy | RHEL's SELinux defaults to enforcing mode (Red Hat docs); "permission denied" with correct modes means check ausearch -m avc |
Fix: prefer capabilities (or sockets handed over by systemd) to setuid; use setgid directories for shared trees; use ACLs sparingly and document them; audit setuid files; when modes look right and access is still denied, check SELinux or AppArmor. Hardening inside containers is Container Security.
The Filesystem Hierarchy Standard: /etc /var /usr /opt /tmp Must-know
In plain words: Linux puts things in agreed places: settings in /etc, changing data in /var, the system's programs in /usr, add-on products in /opt, scratch space in /tmp. Knowing the map tells you where to look and what is safe to delete.
Common misunderstanding: "/tmp is a good place to keep files for a while." It may be a RAM-backed tmpfs, may be cleaned at boot or by a timer, and is shared by every user. Data that must survive a reboot belongs in /var/lib/<app> or /var/tmp.
Definition: The Filesystem Hierarchy Standard (FHS 3.0, Linux Foundation) specifies the layout; hier(7) documents what each directory is for. On the FHS page: "/opt is reserved for the installation of add-on application software packages", and /var/tmp is "Temporary files preserved between system reboots". Modern distributions merge /bin, /sbin and /lib into /usr (symlinks), so /bin/ls and /usr/bin/ls are the same file.
| Path | Holds | Who writes it | For your service |
|---|---|---|---|
/etc | Host-specific configuration, text | root, packages, you | /etc/orders-api/orders-api.env, /etc/systemd/system/*.service |
/usr | Distribution-owned programs, libraries, docs (read-mostly) | package manager | Do not install your own files here; /usr/local is the exception for locally built software |
/usr/local | Software you built or installed outside the package manager | you | Scripts such as /usr/local/libexec/orders-backup.sh |
/opt | Self-contained add-on products, one directory per vendor or package | you, vendor packages | /opt/orders-api/releases/<id>/orders-api and a current symlink |
/var/lib | Persistent state of programs | the service | StateDirectory=orders-api creates /var/lib/orders-api |
/var/log | Logs written as files (journald's binary journal is in /var/log/journal) | services, rsyslog | /var/log/php-fpm-shop/, Nginx logs |
/var/cache | Regenerable cache | the service | Safe to delete; the app must rebuild it |
/var/spool, /var/mail | Queues awaiting processing | MTA, cron | Rarely yours |
/run | Runtime state (PID files, sockets), a tmpfs cleared at boot | services via RuntimeDirectory= | /run/php-fpm-shop/shop.sock |
/tmp, /var/tmp | Scratch; /tmp may be cleared at boot, /var/tmp survives reboots | anyone | Use PrivateTmp=yes so a service gets its own |
/srv | Data served by this system | you | /srv/shop is a common web root |
/home, /root | People's files | users | Services do not live here |
/proc, /sys, /dev | Kernel state, devices (not on disk) | the kernel | Read-mostly; see Priorities and inspection |
where a Go binary and its friends go (a layout, not a command)
/opt/orders-api/releases/20261129T0912Z-ab12cd/orders-api the new build, root:root 0755
/opt/orders-api/current -> releases/20261129T0912Z-ab12cd atomic symlink swap (ln -sfn + mv -T)
/etc/orders-api/orders-api.env root:orders 0640, EnvironmentFile=
/var/lib/orders-api/ state, owned by orders (StateDirectory=)
/run/orders-api/ sockets, PID, owned by orders (RuntimeDirectory=)
/etc/systemd/system/orders-api.service the unit, root:root 0644
journalctl -u orders-api logs: no file path at allReal scenarios: a Laravel app lives in /var/www/shop/releases/<id> with shared/storage and shared/.env symlinked in (the Deployer and Envoyer pattern); an upgrade of the php8.4-fpm package overwrites files in /usr and /etc/php/8.4 but never touches /var/www; a full /var takes down logging and databases while /home has room, which is why /var is often its own filesystem.
Fix: put your software in /opt (or /srv for web roots), configuration in /etc/<app>, state in /var/lib/<app>, and let systemd create the directories with the right owner (StateDirectory=, RuntimeDirectory=, ConfigurationDirectory=, LogsDirectory=). Files under /etc/<app> are yours; files under /usr/lib/systemd/system are the package's, and you override them with drop-ins.
Mounts, fstab, ext4 vs xfs vs btrfs, LVM, swap Important
In plain words: A disk becomes usable when its filesystem is attached ("mounted") at a directory. /etc/fstab lists what to attach at boot. LVM lets you treat several disks as one pool and resize volumes later. Swap is disk space the kernel may use as overflow for memory.
Common misunderstanding: "A bad line in fstab only affects that disk." A wrong or unavailable entry without nofail can drop the machine into emergency mode at boot, and a typo in a remote server means a trip to the console. Test with mount -a (or findmnt --verify) before rebooting.
Definition: fstab(5) has six fields: device (UUID=... is stable, /dev/sdb1 is not), mount point, type, options (defaults,noatime,nofail), fs_freq, and fs_passno ("should be specified with a fs_passno of 1" for the root filesystem, 2 for others, 0 to skip fsck). mount and findmnt show what is attached; lsblk -f shows disks, partitions, filesystem types and UUIDs; df -hT shows usage. LVM adds three layers: physical volumes (PV, a disk or partition), volume groups (VG, a pool), logical volumes (LV, what you format and mount); you extend an LV and its filesystem online with lvextend -r. Swap: swapon --show, a swap file or partition, vm.swappiness ("a value between 0 and 200", default 60).
| Filesystem | Strength | Weakness | Choose it for |
|---|---|---|---|
| ext4 | Mature, default on Debian and Ubuntu, simple repair tools, inode count fixed at creation | Offline shrink only; no snapshots or checksums | General servers, boot and root volumes |
| XFS | Scales to large files and parallel I/O, default on RHEL, dynamic inode allocation, online grow | Cannot shrink | Databases, media, big log volumes, RHEL family |
| Btrfs | Copy-on-write, snapshots, checksums, subvolumes, compression (kernel documentation: "a copy on write filesystem") | More tuning; RAID 5/6 modes have a history of caveats | Workstations, snapshot-heavy setups (Fedora desktop default) |
| tmpfs | In RAM, lost at reboot | Counts against memory | /run, /dev/shm, scratch |
| overlayfs | Layered view over directories | Not a disk filesystem | Container images, see Containers Under the Hood |
| NFS, CIFS | Network filesystems | Latency, D-state hangs when the server vanishes, different locking | Shared media; avoid for databases |
adding a data disk the safe way (illustrative; expected, not run)
1 lsblk -f find the new device, say /dev/vdb, no FSTYPE yet
2 pvcreate /dev/vdb && vgcreate data /dev/vdb && lvcreate -n pg -L 50G data
3 mkfs.xfs /dev/data/pg (or mkfs.ext4)
4 blkid /dev/data/pg copy the UUID
5 echo 'UUID=<uuid> /var/lib/postgresql xfs defaults,noatime,nofail 0 2' >> /etc/fstab
6 systemctl daemon-reload && mount -a && findmnt /var/lib/postgresql
7 later: lvextend -r -L +20G data/pg grow volume and filesystem onlineReal scenarios: /var/lib/docker fills the root disk on a CI runner: give it its own volume; a VM without swap is killed by the OOM killer on a brief spike where 2 GB of swap would have only slowed it; a noexec mount on /tmp breaks an installer that unpacks and runs a binary there; a Kubernetes node sets swap off because the kubelet historically required it.
| Tool | Command | Purpose |
|---|---|---|
| Mount info | findmnt, mount, /proc/mounts | What is mounted, with options |
| Block devices | lsblk -f, blkid | Disks, partitions, UUIDs, filesystem types |
| Usage | df -hT, df -hi | Blocks and inodes per filesystem |
| LVM | pvs, vgs, lvs, lvextend -r | Inspect and grow |
| Swap | swapon --show, free -h, vm.swappiness | Size and eagerness |
| Repair | fsck, xfs_repair (unmounted only) | After a crash |
Fix: mount by UUID with nofail for non-essential disks; give /var/lib/<database>, /var/log and container storage their own volumes; keep a modest swap (it is a buffer, not a plan); use LVM or the cloud's resizable volumes so growth is a command, not a migration.
Inodes, hard and symbolic links, disk usage: df du lsblk Must-know
In plain words: A file's name and its content are separate. The directory holds names; each name points to an inode, which holds the owner, mode, size and where the bytes are. Deleting a name does not delete the bytes while anything else still points at them or has the file open.
Common misunderstanding: "rm frees disk space immediately." It removes one name. If another hard link exists, or any process still has the file open, the space is freed only when the last one goes. A process writing to a log you deleted keeps filling the disk invisibly; df says full while du finds nothing.
Definition: inode(7) lists what an inode holds: device, inode number, mode, link count, owner, group, size, timestamps and block pointers, but not the name. A hard link is another directory entry for the same inode (same filesystem, not for directories); a symbolic link is a tiny file whose content is a path, resolved on use and able to dangle or cross filesystems. df reports filesystem capacity from the superblock; du sums what it can walk; the two disagree when files are deleted but open, when mounts hide files, or with sparse files and snapshots.
"No space left on device", in the order that finds the cause fastest (script: disk-triage.sh)
1 df -hT blocks full on /var? -> du -xh --max-depth=1 /var | sort -h
2 df -hi inodes at 100% (IUse%)? -> millions of small files: find /var -xdev -type f | cut -d/ -f1-4 | sort | uniq -c | sort -n
3 lsof +L1 files with link count 0 still open -> restart the holder (or truncate: : > /proc/<pid>/fd/<n>)
4 mount | grep <path> a mount hiding the real files?
5 tune2fs -m 1 /dev/... ext4 reserves 5% for root by default: tune only if you understand whyReal scenarios:
- Laravel's
storage/framework/cacheor session files create millions of small files;df -hshows free blocks,df -ishows 100% and every write fails. - A Go service logs to
/var/log/orders.log; logrotate deletes and recreates the file but the service keeps the old descriptor (no reopen on SIGHUP): the disk fills while the visible log stays tiny. - A "backup" made with
lninstead ofcpis a second name for the same inode: editing one edits both and a disk failure loses both. ls -lon a symlink shows-> target;deploy/current -> releases/20261129T0912Zis how an atomic switch works.
| Tool | Command | Reads |
|---|---|---|
| Capacity, blocks | df -hT | Superblock of each mounted filesystem |
| Capacity, inodes | df -hi | Same, inode counts |
| Directory sizes | du -xh --max-depth=1 /var | sort -h, ncdu | Walks the tree; -x stays on one filesystem |
| Open deleted files | lsof +L1, ls -l /proc/<pid>/fd | Link count below 1 |
| Block devices | lsblk -f | Disks, partitions, types, UUIDs, mount points |
| One file | stat file, ls -li | Inode number, links, times, mode |
| Links | ln target name, ln -s target name, readlink -f | Create, resolve |
Fix: alert on both block and inode usage; rotate and reopen logs; give caches an expiry and a directory on a filesystem that tolerates many files; use ln -sfn plus mv -T to switch a current symlink atomically (the deploy script in the repository does).
systemd: units, services, targets, systemctl Must-know
In plain words: systemd is the first process (PID 1). It reads small declarative files called units, starts what they describe in the right order, keeps each service in its own resource group, restarts it if it fails, and collects its output.
Common misunderstanding: "systemd is just a faster init.d." It is a service manager with dependencies, cgroup accounting, socket and timer activation, sandboxing and a log pipeline. A unit says what should be true, not which script to run, and the stop command is "kill everything in this cgroup", not "find the PID".
Definition: systemd.unit(5): unit files configure units of many types: service (a process), socket, timer, target (a synchronisation point, like "multi-user"), mount, path, slice. Units are loaded from /usr/lib/systemd/system (package), /etc/systemd/system (administrator, wins), /run/systemd/system (runtime). Dependencies: Wants= (start together, failure tolerated), Requires= (hard), After=/Before= (ordering only: a dependency needs both an ordering and a requirement to behave as expected). systemctl is the client: start, stop, restart, reload, enable (create the WantedBy= symlink so the unit starts at boot), disable, status, is-active, daemon-reload (re-read unit files after you edit them), list-units, list-timers, --failed, cat, edit.
systemctl start orders-api (Type=notify), in order
1 load /etc/systemd/system/orders-api.service and every orders-api.service.d/*.conf drop-in
2 resolve After=network-online.target postgresql.service; start Wants= units first
3 create /var/lib/orders-api, /run/orders-api (StateDirectory=, RuntimeDirectory=), create the cgroup
4 fork, apply User=orders, sandbox (ProtectSystem=strict ...), limits, then execve ExecStart=
5 main process sends READY=1 on $NOTIFY_SOCKET -> state "active (running)" (before that: "activating")
6 Restart=on-failure watches: exit code != 0, killed by signal, WatchdogSec timeout -> wait RestartSec, start again
7 StartLimitBurst=5 in 60 s exceeded -> unit "failed" with result start-limit-hit; systemctl reset-failed to clearReal scenarios:
systemctl status orders-apiprintsActive: activating (start)for 90 seconds thenfailed: the unit isType=notifyand the program never sentREADY=1; fix the program, or useType=simple.- An edit to a unit file has no effect:
systemctl daemon-reloadwas not run (systemctl statuswarns "changed on disk"). - A service starts before the network is configured and fails to bind its address:
After=network-online.targetplusWants=network-online.target;network.targetalone only means "the network stack is up". - A Docker or Podman container is itself supervised by a unit (
docker.service, or a Quadlet.containerfile).
| Command | What it does |
|---|---|
systemctl status orders-api | State, main PID, cgroup tree, last 10 log lines, restart counter |
systemctl enable --now orders-api | Start at boot and start now |
systemctl restart vs reload | Stop and start vs signal the running process (ExecReload=) |
systemctl cat orders-api | The unit with all drop-ins merged and their file paths |
systemctl edit orders-api | Create or edit a drop-in (override.conf) and reload |
systemctl list-dependencies orders-api | The dependency tree |
systemctl --failed, reset-failed | Failed units; clear the failure state |
systemd-analyze verify unit, security unit, blame | Lint a unit, score its sandbox, list boot time by unit |
systemctl get-default, isolate multi-user.target | The boot target; switch targets |
Fix: write a unit, don't script around systemd; after every edit run systemctl daemon-reload; test with systemd-analyze verify; look at systemctl status and journalctl -u first. Alpine and other OpenRC or runit systems use different files; the ideas (supervised, declarative, per-service user) carry over.
Writing a service unit: environment files, hardening, limits Must-know
In plain words: A good unit file names the program, the user it runs as, how to know it is ready, when to restart it, how long to wait on stop, where its settings come from, and what it must not be allowed to touch.
Common misunderstanding: "Environment= and EnvironmentFile= are a shell." They are not: no export, no $VAR expansion between lines, no command substitution; quoting rules are systemd's. Also ulimit in a shell profile or /etc/security/limits.conf does nothing for a service (see Limits).
Definition: EnvironmentFile= reads KEY=value lines; a leading - on the path makes a missing file non-fatal. Type=notify waits for READY=1. Restart=on-failure restarts after a non-zero exit, a signal, a timeout or a watchdog expiry but not after a clean stop. TimeoutStopSec= bounds the stop; afterwards systemd sends SIGKILL to what remains in the cgroup ("the termination request is repeated with the SIGKILL signal"). StateDirectory= creates /var/lib/<name> owned by the service user. NoNewPrivileges=yes blocks setuid escalation; ProtectSystem=strict mounts the whole file system hierarchy read-only except /dev, /proc, /sys and what ReadWritePaths= and the *Directory= settings name; PrivateTmp=yes gives a private /tmp; MemoryMax= is the cgroup hard limit; OOMPolicy=stop stops the unit when one of its processes is OOM-killed. systemd-analyze security orders-api scores how exposed a unit is.
# /etc/systemd/system/orders-api.service
# A Go binary as a hardened, supervised service. Edit with `systemctl edit`,
# never by hand in /usr/lib; verify with `systemd-analyze verify` and `systemd-analyze security`.
[Unit]
Description=Orders API (Go)
Documentation=https://wiki.example.com/runbooks/orders-api
# Wait for the network to be configured (not merely "up") and for the database unit if it runs on this host.
After=network-online.target postgresql.service
Wants=network-online.target
# Give up after 5 failed starts in 60 s instead of looping forever (these two belong in [Unit]).
StartLimitIntervalSec=60
StartLimitBurst=5
[Service]
# Type=notify: the service is "started" only when it sends READY=1 (see service/notify.go).
Type=notify
NotifyAccess=main
User=orders
Group=orders
ExecStart=/opt/orders-api/current/orders-api
# SIGHUP makes the app re-read CONFIG_FILE; no restart, no dropped connections.
ExecReload=/bin/kill -HUP $MAINPID
# KEY=value lines, no "export", no shell expansion. A leading "-" would make a missing file non-fatal.
EnvironmentFile=/etc/orders-api/orders-api.env
Environment=ADDR=127.0.0.1:8080
# Restart only on failure (non-zero exit, signal, timeout, watchdog), not after a clean `systemctl stop`.
Restart=on-failure
RestartSec=2s
# The app drains for 8 s; allow 15 s before systemd sends SIGKILL to what is left.
TimeoutStopSec=15s
# The app pings WATCHDOG=1 at half this interval; a hung process is killed and restarted.
WatchdogSec=30s
# Directories systemd creates with the right owner: /var/lib/orders-api, /run/orders-api, /etc/orders-api (read-only to the service).
StateDirectory=orders-api
RuntimeDirectory=orders-api
ConfigurationDirectory=orders-api
WorkingDirectory=/var/lib/orders-api
# Resource limits: the service's own cgroup, not a per-process ulimit alone.
LimitNOFILE=65536
MemoryHigh=384M
MemoryMax=512M
TasksMax=512
# If the kernel OOM killer kills one process in this cgroup, stop the whole unit (then Restart= brings it back).
OOMPolicy=stop
# Sandbox: a web service needs almost none of what a login user has.
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
CapabilityBoundingSet=
AmbientCapabilities=
SystemCallArchitectures=native
SystemCallFilter=@system-service
UMask=0027
[Install]
WantedBy=multi-user.targetreading what a unit actually runs (all standard commands)
1 systemctl cat orders-api.service source of truth with drop-ins
2 systemd-analyze verify /etc/systemd/system/orders-api.service typos, missing files, wrong sections
3 systemd-analyze security orders-api.service exposure score and a list of settings that would lower it
4 systemctl show orders-api -p MainPID,MemoryCurrent,NRestarts,Result,ExecMainStatus
5 systemd-cgls /system.slice/orders-api.service the processes in the unit's cgroupReal scenarios:
- A deployment writes
/etc/orders-api/orders-api.envwithDATABASE_URL; the unit reads it as the service user because the file isroot:orders 0640. A secret inEnvironment=would sit in a world-readable unit file and insystemctl showoutput. - A restart storm:
Restart=alwayswith noRestartSecand no start limit restarts a crashing Go binary every 100 ms (the documented defaultRestartSec) until the manager's default start limit (DefaultStartLimitIntervalSecandDefaultStartLimitBurst, inherited when the unit sets nothing) trips; setRestartSecandStartLimitBurst/StartLimitIntervalSec(in[Unit]) deliberately, since an interval of 0 disables limiting altogether. - A service needs to write one directory: with
ProtectSystem=strictaddReadWritePaths=/srv/uploadsorStateDirectory=; "Read-only file system" errors after hardening mean exactly this. - A memory leak is contained by
MemoryMax=512M: the kernel kills inside the cgroup,OOMPolicy=stopends the unit cleanly,Restart=on-failurebrings a fresh one.
| Setting | Effect | Use when |
|---|---|---|
Type=simple, exec, forking, oneshot, notify | When systemd considers the unit started | notify for programs that can send READY=1; oneshot for jobs |
User=, Group=, DynamicUser=yes | Run as a non-root user; DynamicUser allocates a transient UID | Every service; dynamic users when you want no account to manage |
Restart=, RestartSec=, StartLimitBurst= | Recovery policy | on-failure for daemons, none for one-shots |
ExecReload= | What systemctl reload runs | The program can re-read config on a signal |
TimeoutStopSec=, KillSignal=, KillMode= | How the stop is escalated | KillSignal=SIGQUIT for PHP-FPM; default control-group otherwise |
LimitNOFILE=, LimitNPROC= | Per-process rlimits | High-connection servers |
MemoryHigh=, MemoryMax=, CPUQuota=, TasksMax= | cgroup limits | Noisy neighbours; protect the box |
NoNewPrivileges=, ProtectSystem=, ProtectHome=, PrivateTmp=, RestrictAddressFamilies=, SystemCallFilter=, CapabilityBoundingSet= | Sandbox | Always start from systemd-analyze security |
Environment=, EnvironmentFile= | Variables | Non-secret and secret respectively (file with tight mode); LoadCredential= for real secrets |
Fix: copy the repository's orders-api.service, delete what the program does not need, run systemd-analyze security, and keep the file in version control (rendered by Ansible or cloud-init; see Configuration Management). Compare it with orders-api.before.service, the version most teams start with, which is wrong in eight listed ways.
# The unit most teams start with. It runs, and it is wrong in eight ways (each line says how).
[Unit]
Description=orders api
[Service]
# 1. no User=: the service runs as root, so a bug in the app is a root bug
ExecStart=/home/ubuntu/orders-api/orders-api
# 2. a path in a login user's home: breaks when that account is removed, and ProtectHome could never be enabled
WorkingDirectory=/home/ubuntu/orders-api
# 3. secrets inline in the unit file, which is world-readable under /etc/systemd/system
Environment=DATABASE_URL=postgres://orders:s3cret@127.0.0.1/orders
# 4. Restart=always with no RestartSec: a crash loop restarts every 100 ms (the default RestartSec) until the inherited
# default start limit (DefaultStartLimitIntervalSec/Burst) trips and the unit fails; set both deliberately
Restart=always
# 5. Type=simple: "started" the moment the process forks, long before the port is open
# 6. no TimeoutStopSec and no handler: the default stop timeout then SIGKILL, dropping in-flight requests
# 7. no limits: the default open-file limit (1024 soft in many setups) and no memory cap
# 8. no sandbox: the process can read /home, write /etc and see every other process's files
[Install]
WantedBy=multi-user.targetTimers vs cron Important
In plain words: Both run a command on a schedule. A cron line is one line in a table; a systemd timer is a pair of units (a timer and the service it triggers), which means logs, limits, dependencies and "run once if the machine was off" come for free.
Common misunderstanding: "Cron is simpler, so it is better." Cron is shorter to write and poorer to operate: it mails output nobody reads, has no overlap protection, runs with a minimal environment (PATH is short), and silently skips jobs missed while the machine was down. A timer also adds nothing you do not ask for: it is not "better" for a one-line job on a box you already manage with cron.
Definition: systemd.timer(5): OnCalendar= is a calendar expression (*-*-* 02:30:00, hourly, Mon..Fri 09:00; test with systemd-analyze calendar), OnBootSec=/OnUnitActiveSec= are relative (monotonic) timers, RandomizedDelaySec= spreads load, AccuracySec= (default one minute) lets the timer coalesce wake-ups, and Persistent=: "If true, the time when the service unit was last triggered is stored on disk. When the timer is activated, the service unit is triggered immediately if it would have been triggered at least once during the time when the timer was inactive." The service it triggers is usually Type=oneshot.
# /etc/systemd/system/orders-backup.timer
# Replaces a crontab line "30 2 * * *". Enable the timer, not the service:
# systemctl enable --now orders-backup.timer ; systemctl list-timers
[Unit]
Description=Nightly orders database dump (timer)
[Timer]
OnCalendar=*-*-* 02:30:00
# Spread many machines over ten minutes so they do not hit the database server together.
RandomizedDelaySec=10min
# If the machine was off at 02:30, run once at the next boot (cron would silently skip it).
Persistent=true
[Install]
WantedBy=timers.target# /etc/systemd/system/orders-backup.service
# A one-shot job: runs to completion, then is "inactive (dead)". Started by orders-backup.timer, or by hand:
# systemctl start orders-backup.service
[Unit]
Description=Nightly orders database dump
[Service]
Type=oneshot
User=orders
Group=orders
ExecStart=/usr/local/libexec/orders-backup.sh
# Lower CPU and disk priority so the dump does not compete with live traffic.
Nice=10
IOSchedulingClass=idle
PrivateTmp=yes
ProtectSystem=strict
ReadWritePaths=/var/backups/orders| Aspect | cron (crontab -e, /etc/cron.d) | systemd timer |
|---|---|---|
| Definition | One line, five time fields | Two unit files |
| Logs | Mail or a redirect you write | journalctl -u orders-backup, with exit status |
| Missed run (machine off) | Skipped (anacron is a separate tool) | Persistent=true catches up once |
| Overlap | Starts a second copy | A running oneshot is not started again |
| Environment | Minimal, differs from a login shell | Defined by the unit; same as any service |
| Limits, sandbox, priority | nice by hand | Nice=, MemoryMax=, ProtectSystem= ... |
| Jitter | Needs sleep $RANDOM | RandomizedDelaySec= |
| Observability | grep CRON /var/log/syslog | systemctl list-timers shows last and next run |
| Portability | Every Unix | systemd only |
Real scenarios: a nightly dump started by cron at 02:30 on 200 VMs hits the database server together; RandomizedDelaySec=10min removes the spike. A cron-run Laravel scheduler hides failures in /dev/null; the timer version logs every tick (the repository's laravel-schedule.timer, see Laravel).
Fix: use a timer for anything you must observe, limit or catch up; keep cron where the platform has no systemd or the job is trivial; always set Persistent= deliberately, and give long jobs a TimeoutStartSec.
Logs: rsyslog and journald, journalctl, logrotate Must-know
In plain words: Services should write their logs to stdout or stderr and let the system keep them. systemd's journal stores them with metadata (which unit, which user, how severe); rsyslog, if present, writes classic text files in /var/log. Rotation keeps the files from filling the disk.
Common misunderstanding: "If the app writes /var/log/app.log itself, rotation just works." Rotation renames or truncates the file; the process must be told to reopen it, or it keeps writing to the renamed (or deleted) file. A service that logs to stderr under systemd needs no file, no rotation and no reopen.
Definition: systemd-journald collects stdout and stderr of services, kernel messages (journalctl -k), and syslog. Storage is Storage=persistent (in /var/log/journal) or volatile in /run/log/journal; SystemMaxUse= bounds the size (journald.conf(5)). journalctl -u unit, -f follow, -p err priority, --since "1 hour ago", -b this boot, -b -1 previous boot, -o json structured, -k kernel. rsyslog receives syslog messages and writes /var/log/syslog, /var/log/auth.log (Debian) or /var/log/messages, /var/log/secure (RHEL); it can forward to a central server. logrotate(8) rotates files on a schedule (weekly, rotate 8, compress, delaycompress, copytruncate, postrotate scripts) from /etc/logrotate.d/; logrotate -d is a dry run.
# /etc/logrotate.d/shop (test without rotating: logrotate -d /etc/logrotate.d/shop ; force: logrotate -f ...)
/var/www/shop/shared/storage/logs/*.log /var/log/php-fpm-shop/*.log {
weekly
rotate 8
# Keep the newest rotated file uncompressed: a process may still be writing to it for a moment.
compress
delaycompress
missingok
notifempty
create 0640 www-data adm
sharedscripts
postrotate
# FPM reopens its log files on SIGUSR1 (php-fpm(8)); the app's own Laravel "daily" channel needs nothing.
/bin/kill -USR1 $(cat /run/php-fpm-shop/php-fpm.pid 2>/dev/null) 2>/dev/null || true
endscript
}# /etc/systemd/journald.conf.d/10-retention.conf (apply: systemctl restart systemd-journald)
[Journal]
# Persistent: keep /var/log/journal across reboots (the default "auto" only does so if the directory already exists).
Storage=persistent
SystemMaxUse=1G
SystemKeepFree=2G
MaxRetentionSec=1month
# Rate limit per service so one noisy loop cannot push everyone else out of the journal.
RateLimitIntervalSec=30s
RateLimitBurst=10000where one request's evidence lives (a Go service and PHP-FPM on one host)
1 Go service: slog text to stderr -> journald -> journalctl -u orders-api --since "10 min ago" -p warning
2 PHP-FPM: error_log = syslog -> journald/rsyslog; slow requests -> /var/log/php-fpm-shop/slow.log
3 Nginx: /var/log/nginx/access.log and error.log (files), rotated by /etc/logrotate.d/nginx (USR1 reopens)
4 Laravel: storage/logs/laravel.log (single) or laravel-YYYY-MM-DD.log (daily channel; retention LOG_DAILY_DAYS)
5 Kernel: journalctl -k, dmesg -T: OOM kills, disk errors, firewall drops
6 one ID across them: log a request ID everywhere (see the observability chapter)Real scenarios: a disk fills because journald was never bounded; SystemMaxUse=1G fixes it for good. A deploy "lost" logs because the journal was volatile and the host rebooted: Storage=persistent. A debugging session wants "everything from the last crash": journalctl -u orders-api -b -1 -e. A noisy debug loop is dropped by journald's rate limit and the line "Suppressed N messages" appears: raise it for that unit with LogRateLimitIntervalSec= and LogRateLimitBurst=.
| Source | Where | Rotation | Reopen |
|---|---|---|---|
| journald | /var/log/journal or /run/log/journal | Built-in (SystemMaxUse=, MaxRetentionSec=) | n/a |
| rsyslog files | /var/log/syslog, messages, auth.log | logrotate | postrotate HUP or rsyslog-rotate |
| Nginx | /var/log/nginx/*.log | logrotate | USR1 |
| PHP-FPM | error_log, slowlog, access log | logrotate | USR1 |
| Laravel | storage/logs | daily channel with days, or logrotate | the app reopens per request |
| Go service | stderr | journald | n/a |
Fix: stderr plus journald for services you write; persistent bounded journal; logrotate with a reopen for software that insists on files; ship logs off the box for anything you will need after the box is gone. The concepts (structured logs, levels, correlation) are in Observability, and the Go logging API in CLI Flags, Environment Variables & Logging.
Memory, free, the OOM killer, oom_score_adj Must-know
In plain words: Linux uses spare RAM to cache files and hands it back when programs need it, so "free" is always small and that is healthy. When programs ask for more than exists and nothing can be reclaimed, the kernel kills a process to survive: the OOM killer.
Common misunderstanding: "The OOM killer killed my app because it used the most memory, so I need less memory." It kills the process with the highest badness score: memory use (RSS, swap, page tables) adjusted by oom_score_adj. A small service next to a big database can die first if its adjustment is higher, and a container or service with a MemoryMax is killed inside its own cgroup even when the host has plenty.
Definition: free(1): used is "Used or unavailable memory (calculated as total - available)", available is the estimate of how much can be started "without swapping". Per process: /proc/<pid>/oom_score (read-only badness) and oom_score_adj: "The value of oom_score_adj is added to the badness score before it is used to determine which task to kill. Acceptable values range from -1000 (OOM_SCORE_ADJ_MIN) to +1000 (OOM_SCORE_ADJ_MAX)", where -1000 "is equivalent to disabling OOM-killing entirely for that task". In systemd: OOMScoreAdjust=, MemoryMax= (cgroup limit; breaching it triggers a cgroup OOM), MemoryHigh= (throttle first), OOMPolicy=. Kernel vm.overcommit_memory (0 heuristic default, 1 always, 2 never) decides whether an allocation is refused up front; vm.swappiness ("a value between 0 and 200", default 60) balances swap against page cache.
a process disappears with exit status 137 (illustrative; expected, not run)
1 journalctl -u orders-api -n 20 "orders-api.service: Main process exited, code=killed, status=9/KILL"
2 dmesg -T | grep -i -E 'killed process|out of memory'
Out of memory: Killed process 4821 (orders-api) total-vm:... anon-rss:... oom_score_adj:0
(a cgroup kill says "Memory cgroup out of memory" and names the cgroup path)
3 systemctl show orders-api -p MemoryMax,MemoryCurrent,Result Result=oom-kill (with OOMPolicy=stop)
4 free -m available near zero? swap used? -> host-wide shortage
5 cat /proc/meminfo | grep -E 'MemAvailable|SwapFree|Committed_AS'Real scenarios:
- A PHP-FPM pool with
pm.max_children = 100and 80 MB per worker needs 8 GB at peak; on a 4 GB VM the kernel kills a worker, then the master, in a loop. Sizemax_childrenfrom measured RSS:ps --no-headers -o rss -C php-fpm8.4 | awk '{s+=$1} END {print s/NR/1024 " MB avg"}'. - A Go service with a goroutine leak climbs to its
MemoryMaxand is killed;GOMEMLIMIT=600MiB(a soft memory limit, added in Go 1.19) makes the garbage collector work harder as the heap approaches the limit. It is soft: the Go GC guide says memory use may surpass it to avoid GC thrashing, so it is not a guarantee. Set it belowMemoryMax, which remains the wall. - A database is protected with
OOMScoreAdjust=-900so the kernel prefers to kill workers; a sacrificial job getsOOMScoreAdjust=500. - A VM with
vm.overcommit_memory=2refuses allocations early and apps fail with "Cannot allocate memory" whilefreeshows plenty: the commit limit, not RAM, is the cause.
| Signal | Where to see it | Meaning |
|---|---|---|
available low and falling | free -m, MemAvailable | Real shortage; cache is already gone |
si/so non-zero | vmstat 1 | Swapping in/out: the machine is thrashing |
Result=oom-kill, exit 137 | systemctl status, journal | A service was killed for memory |
Out of memory: Killed process | dmesg -T, journalctl -k | The global OOM killer |
memory.events oom_kill count | /sys/fs/cgroup/<unit>/memory.events | Kills inside one cgroup |
memory.pressure (PSI) | /proc/pressure/memory | Time spent stalled for memory; the early warning |
Fix: alert on MemAvailable, not free; give every service a MemoryMax slightly above its normal peak and a MemoryHigh below it; set GOMEMLIMIT for Go and memory_limit/pm.max_children for PHP from measurements; keep a little swap as a shock absorber; do not disable the OOM killer, scope it. Kernel-level memory debugging is Linux Debugging.
CPU, load average, steal, iostat vmstat sar, PSI Important
In plain words: Load average is how many tasks, over the last 1, 5 and 15 minutes, were running or waiting to run (and, on Linux, waiting for disk). It is not CPU percentage. Whether it is high depends on how many CPUs you have.
Common misunderstanding: "Load 8 means the CPU is 800% busy" or "load is high so the CPU is the bottleneck". On Linux, tasks blocked on disk or NFS count too, so a load of 8 with an idle CPU often means a slow disk. Brendan Gregg: Linux changed load averages "to include not only runnable tasks, but also tasks in the uninterruptible state", and "Except they aren't really averages, and they aren't 1, 5, and 15 minutes" (they are exponentially damped sums).
Definition: Compare load with CPU count (nproc): load per CPU above about 1 for sustained periods means queueing. top's summary line shows us sy ni id wa hi si st: user, system, nice, idle, wa I/O wait, hardware and software interrupts, and st steal: time the hypervisor gave your virtual CPU to another guest (a noisy neighbour on shared hosts). vmstat 1: r runnable, b blocked, si/so swap, bi/bo blocks, us/sy/id/wa/st. iostat -xz 1: per-device r/s w/s, await ("the average time (in milliseconds) for I/O requests"), aqu-sz, %util. sar records history (sar -u, -r, -n DEV, -q) when sysstat collects. PSI (/proc/pressure/{cpu,memory,io}, kernel "Pressure Stall Information") reports the share of time tasks stalled, which is closer to user pain than load.
#!/bin/sh
# triage-60s.sh: the first minute of a Linux performance investigation (Brendan Gregg's ten commands) in one file.
# Each command has a one-line question; read the output top to bottom. Output is also saved for the ticket.
# usage: sh triage-60s.sh [outfile]
out=${1:-/tmp/triage-$(hostname)-$(date +%Y%m%dT%H%M%S).txt}
run() { printf '\n### %s\n' "$*"; "$@" 2>&1; }
{
run uptime # load averages: rising or falling? (1, 5, 15 minutes)
run sh -c 'dmesg -T | tail -n 15' # kernel complaints: OOM kills, disk errors, TCP drops
run vmstat 1 5 # r > CPUs? si/so non-zero (swapping)? us/sy/id/wa/st split
run mpstat -P ALL 1 3 # one hot CPU (single-threaded bottleneck) or all busy?
run pidstat 1 3 # which process uses the CPU
run iostat -xz 1 3 # %util, await, queue size per disk
run free -m # "available" matters, not "free"
run sar -n DEV 1 3 # network throughput per interface
run sar -n TCP,ETCP 1 3 # retransmits, new connections
run top -b -n 1 -o %CPU # summary of the above
} | tee "$out"
echo "saved: $out"the first minute of an investigation (script above; expected, not run)
1 uptime load 1/5/15: rising (trouble coming) or falling (recovering)?
2 dmesg -T | tail OOM kills, I/O errors, NIC resets
3 vmstat 1 5 r above CPU count? si/so non-zero? wa high? st high?
4 mpstat -P ALL 1 3 one CPU at 100% = single-thread bottleneck; all busy = capacity
5 pidstat 1 3 which process
6 iostat -xz 1 3 await in tens of ms or %util near 100 = storage
7 free -m available
8 sar -n DEV 1 3 ; sar -n TCP,ETCP 1 3 throughput, retransmits
9 top confirmReal scenarios: a 2-vCPU VM shows load 6 with 5% CPU used and 90% wa: a backup is reading the same disk. A burstable cloud instance shows rising st after its CPU credits run out. A Go service pinned at 100% on one core of 8 is a lock or a single hot goroutine, not a capacity problem. A load of 0.00 with timeouts is not a CPU problem at all: go to Network basics.
| Metric | Healthy shape | Suspect when | Tool |
|---|---|---|---|
| Load per CPU | below 1 sustained | above 1 for minutes | uptime, /proc/loadavg |
%usr + %sys | headroom | near 100 on one or all CPUs | mpstat -P ALL |
%wa | low | tens of percent | vmstat, iostat |
%st | near 0 | sustained above a few percent | top, vmstat |
await, aqu-sz | low ms, small queue | long waits, deep queue | iostat -xz |
context switches cs | stable | spikes with load | vmstat, pidstat -w |
PSI some/full | near 0 | rising avg10 | /proc/pressure/* |
Fix: read load with CPU count and the wa/st columns; record history (sysstat, node_exporter) so "slow yesterday" can be answered; use the USE method (utilisation, saturation, errors per resource). Profiling and tracing are Linux Debugging.
Network basics (ip, ss, dig) link to the networking chapters Important
In plain words: Three commands answer most first questions: ip ("what addresses and routes does this machine have?"), ss ("who is listening and who is connected?"), and dig ("what does DNS say?").
Common misunderstanding: "localhost:8080 works, so the service is reachable." A service bound to 127.0.0.1 is reachable only from the same host; to accept connections it must listen on 0.0.0.0 or a specific interface address, and a firewall or security group must also allow it. ss -ltnp shows the bound address.
Definition: ip(8) "show / manipulate routing, network devices, interfaces and tunnels" (ip -br addr, ip route, ip -s link). ss(8) "is used to dump socket statistics" (ss -ltnp TCP listeners with owning processes, ss -tn state established '( dport = :5432 )', ss -s summary). dig queries a DNS server directly (dig +short A example.com, dig @1.1.1.1 example.com, dig -x 203.0.113.10). The theory (addressing, NAT, DNS, TCP states, firewalls, VPNs) is in the networking chapters: IP Addressing, DNS Resolution, Ports, Sockets & Connections, Firewalls and Network Troubleshooting Playbook.
"connection refused" vs "timed out", on the server (illustrative)
1 ss -ltnp | grep 8080 nothing listens -> refused (the kernel answers RST)
2 ss -ltnp 0.0.0.0:8080 users:(("orders-api",pid=4821,fd=3)) <- fd 3: socket from systemd
3 curl -sv 127.0.0.1:8080/healthz local works, remote fails -> bind address or firewall
4 ip -br addr ; ip route get 203.0.113.10 which interface and gateway would be used
5 dig +short db.internal name resolves? to what? (resolvectl status shows the resolver in use)
6 ss -tn state established '( dport = :5432 )' | wc -l how many DB connections does this host holdReal scenarios: after a deploy the app answers on the VM but not from the load balancer: it listens on 127.0.0.1. A Go service shows 28,000 sockets in TIME-WAIT after a load test: connection reuse (http.Transport keep-alive) is missing. DNS works for dig but not for the app: the app uses the system resolver (/etc/resolv.conf, systemd-resolved) while dig queries the server you named.
| Question | Command |
|---|---|
| My addresses and routes | ip -br addr, ip route |
| What is listening | ss -ltnp, ss -lunp (UDP) |
| Who is connected to me | ss -tn state established |
| Does DNS answer | dig +short <name>, getent hosts <name> (what applications use) |
| Is a remote port open | nc -vz host port, curl -v telnet://host:port |
| Which path do packets take | ip route get <ip>, mtr, traceroute |
Fix: know the three; bind deliberately; test the same way the application resolves (getent hosts); keep the rest in the networking chapters.
SSH: keys, ~/.ssh/config, sshd hardening Must-know
In plain words: SSH logs you in to another machine over an encrypted connection. A key pair replaces the password: the private half stays on your laptop, the public half is listed on the server.
Common misunderstanding: "The server's host key warning is noise, I'll accept it." The first connection records the server's key in ~/.ssh/known_hosts; a later mismatch means either the server was rebuilt or someone is impersonating it. Verify the fingerprint through another channel (cloud console, provisioning log) before accepting or removing the old entry.
Definition: ssh-keygen -t ed25519 -C "laptop-2026" creates a key pair; ~/.ssh/authorized_keys on the server lists accepted public keys; permissions matter: ~/.ssh is 0700, private keys 0600, authorized_keys not writable by others (sshd refuses otherwise with StrictModes). ~/.ssh/config gives hosts nicknames and options: HostName, User, IdentityFile, IdentitiesOnly yes, ProxyJump (a bastion), ControlMaster auto plus ControlPersist (reuse one connection), ServerAliveInterval. sshd_config hardening basics: PermitRootLogin no, PasswordAuthentication no, KbdInteractiveAuthentication no, PubkeyAuthentication yes, AllowUsers, MaxAuthTries, X11Forwarding no; check with sshd -t, apply with a reload, and keep one session open while you test another. Agent forwarding (ssh -A) exposes your keys to root on the remote host; prefer ProxyJump.
# /etc/ssh/sshd_config.d/10-hardening.conf (check: sshd -t ; apply: systemctl reload ssh (Debian) / sshd (RHEL))
# Keep an existing session open while you test a new one: a typo here can lock you out.
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
AllowUsers deploy
MaxAuthTries 3
LoginGraceTime 20
X11Forwarding no
AllowAgentForwarding no
# Drop dead connections: probe every 5 minutes, give up after 2 missed answers.
ClientAliveInterval 300
ClientAliveCountMax 2# ~/.ssh/config (mode 0600; OpenSSH reads the first value it finds for each option, so specific Host blocks go first)
Host prod-web
HostName 203.0.113.10
User deploy
IdentityFile ~/.ssh/id_ed25519_prod
# Offer only this key, not every key the agent holds (avoids "Too many authentication failures").
IdentitiesOnly yes
# Reach a private host through a bastion in one command: ssh prod-db
Host prod-db
HostName 10.0.4.20
User deploy
ProxyJump prod-web
IdentityFile ~/.ssh/id_ed25519_prod
IdentitiesOnly yes
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
# Reuse one TCP connection for repeated ssh/scp/rsync to the same host.
ControlMaster auto
ControlPath ~/.ssh/cm-%C
ControlPersist 10mgetting a key onto a new server without ever typing a password twice (expected, not run)
1 ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_prod -C "alice@laptop 2026" passphrase: yes
2 ssh-copy-id -i ~/.ssh/id_ed25519_prod.pub deploy@203.0.113.10 one last password
3 ssh -o PasswordAuthentication=no deploy@203.0.113.10 true proves the key works
4 put 10-hardening.conf in /etc/ssh/sshd_config.d/ ; sshd -t ; systemctl reload ssh
5 in a second terminal: ssh prod-web (must succeed) ; only then close the first session
6 ssh-add -l ; ssh-add -t 1h ~/.ssh/id_ed25519_prod agent with a lifetimeReal scenarios: Too many authentication failures: the agent offered six keys before the right one; IdentitiesOnly yes. A CI job deploys with a key restricted in authorized_keys by command="/usr/local/bin/deploy",no-pty,no-port-forwarding. A bastion with ProxyJump replaces a VPN for a private database host; tunnels and WireGuard are in VPNs & Tunnels. Brute-force noise in auth.log is why password logins are off and why fail2ban or a firewall rate-limit helps.
| Concern | Setting or tool |
|---|---|
| Key type | Ed25519 (small, fast); RSA 3072+ where required |
| Passphrase | Always; load with ssh-agent or the OS keychain |
| Server config location | /etc/ssh/sshd_config and /etc/ssh/sshd_config.d/*.conf (first value wins; the distribution's include line is at the top) |
| Service name | ssh on Debian and Ubuntu, sshd on RHEL and Fedora |
| Per-key restrictions | command=, from=, no-agent-forwarding in authorized_keys |
| Audit | journalctl -u ssh, last, lastb, /var/log/auth.log or secure |
| Certificates | ssh-keygen -s ca_key signs short-lived user and host certificates |
Fix: keys not passwords; a non-root login user with sudo; AllowUsers; one config drop-in under sshd_config.d; sshd -t before every reload; rotate and revoke keys when people leave; read Network Troubleshooting Playbook when the TCP connection itself fails.
ulimit and limits.conf, file descriptors Important
In plain words: The kernel caps what one process may use: how many files and sockets it may hold open, how many processes it may start, how much memory it may lock. "Too many open files" is the most common hit.
Common misunderstanding: "I raised the limit in /etc/security/limits.conf so my service has it." That file is read by PAM (pam_limits) when a login session opens. A service started by systemd never goes through PAM, so it gets LimitNOFILE= from its unit (or the manager's default) instead. Check what a running process really has: cat /proc/<pid>/limits.
Definition: getrlimit(2): each resource has a soft limit (enforced) and a hard limit (the ceiling an unprivileged process may raise the soft one to): RLIMIT_NOFILE (open descriptors), RLIMIT_NPROC, RLIMIT_CORE, RLIMIT_MEMLOCK, RLIMIT_STACK. Shell: ulimit -n (soft), ulimit -Hn (hard), ulimit -n 65536. limits.conf(5): lines domain type item value such as orders hard nofile 65536. systemd: LimitNOFILE=, LimitNPROC=, LimitCORE=; cgroup limits TasksMax=, MemoryMax=. System-wide ceilings: fs.file-max, fs.nr_open. A file descriptor is a small integer naming an open file, socket, pipe or epoll instance; each TCP connection costs one in the process that holds it. Since Go 1.19 programs that import os "change the soft limit to match the hard limit" at start-up, which is why Go services hit the hard limit, not the soft one.
# /etc/security/limits.d/90-orders.conf
# Read by pam_limits when a PAM session opens (ssh login, su, cron on most distributions).
# It does NOT apply to a service started by systemd: use LimitNOFILE= in the unit for those.
# <domain> <type> <item> <value>
orders soft nofile 8192
orders hard nofile 65536
@developers soft nproc 4096diagnosing "accept: too many open files" (illustrative)
1 systemctl show orders-api -p LimitNOFILE LimitNOFILE=65536 (the unit's setting)
2 cat /proc/$(systemctl show -p MainPID --value orders-api)/limits | grep 'open files'
3 ls /proc/<pid>/fd | wc -l current use; grows with connections or a leak
4 ls -l /proc/<pid>/fd | awk '{print $NF}' | sort | uniq -c | sort -rn | head what they are
5 fix the leak (unclosed response bodies, missing defer Close) or raise LimitNOFILE and restartReal scenarios: a Go HTTP client that never closes resp.Body leaks one descriptor per request until dial tcp: socket: too many open files. Nginx workers need worker_rlimit_nofile above worker_connections. A database on a shell-started process works, and under systemd fails: the limits differ. A CI container runs with a 1024 soft limit and a build tool with 5,000 parallel files fails; ulimit -n inside the container shows it.
| Where | Applies to | Set by |
|---|---|---|
ulimit -n | The current shell and its children | You, per session |
/etc/security/limits.d/*.conf | PAM login sessions (ssh, su, console) | Administrator |
LimitNOFILE= in a unit or drop-in | That service | Unit author |
DefaultLimitNOFILE= in /etc/systemd/system.conf | All services without their own | Administrator |
Container runtime flags (--ulimit) | One container | Runtime config |
fs.file-max, fs.nr_open (sysctl) | System-wide ceilings | Administrator |
Fix: set LimitNOFILE in the unit; verify through /proc/<pid>/limits; fix leaks first, then raise limits; alert on descriptors in use versus the limit. The repository's limits-orders.conf is the PAM version and says in its header that it does not reach services.
Time, NTP, chrony, locales and timezones Important
In plain words: A server's clock drifts, and a wrong clock breaks TLS certificates, token expiry, logs, database replication and cron. A time-sync daemon (chrony) keeps it right. The timezone only changes how the time is shown, not what it is.
Common misunderstanding: "Set the server to my local timezone so logs are readable." Servers should run in UTC; convert at the edge. Local time has a repeated hour and a missing hour at every daylight-saving change, so logs are ambiguous and schedulers misfire. And changing the timezone never changes the clock itself: Unix time is seconds since the epoch, always UTC.
Definition: NTP daemons measure the offset to reference servers and steer the clock (slew gradually, step when far off). chrony is the default on RHEL, Fedora and most cloud images; systemd-timesyncd is a lighter SNTP client on Debian and Ubuntu desktops and images. chrony's makestep "forces chronyd to step the system clock if the adjustment is larger than a threshold value, but only if there were no more clock updates since chronyd was started than the specified limit" (counted from when chronyd started, so a restarted chronyd may step again), pool ... iburst uses several servers with a fast start, rtcsync copies time to the hardware clock; chronyc tracking, chronyc sources -v show the state. timedatectl shows and sets the timezone and NTP status (timedatectl set-timezone UTC, timedatectl set-ntp true). Locale: LANG and LC_* select language, sorting and number format; locale -a lists generated locales; localectl set-locale LANG=en_US.UTF-8; for programs and databases prefer C.UTF-8 or en_US.UTF-8 consistently, because collation affects sorting, indexes and LIKE behaviour.
# /etc/chrony/chrony.conf (Debian/Ubuntu path; /etc/chrony.conf on RHEL/Fedora)
# Pool = several servers behind one DNS name; iburst sends a quick burst of 4 requests at start-up.
pool 2.pool.ntp.org iburst maxsources 4
# Step the clock (instead of slewing it slowly) if it is off by more than 1 s, but only during the first 3 updates.
makestep 1.0 3
# Record the measured oscillator error so the next boot starts accurate.
driftfile /var/lib/chrony/chrony.drift
# Copy the system time to the hardware clock every 11 minutes (kernel RTC sync).
rtcsyncchecking and fixing the clock (expected, not run)
1 timedatectl "System clock synchronized: yes", "NTP service: active", Time zone: Etc/UTC
2 chronyc tracking "System time : 0.000012 seconds fast of NTP time" (shape)
3 chronyc sources -v one source marked '*' (selected), reach 377
4 sudo timedatectl set-timezone UTC
5 date -u ; date ; TZ=Asia/Tehran date the same instant, three presentationsReal scenarios: JWT validation fails intermittently on one host: its clock is 90 seconds behind. A VM restored from a snapshot jumps in time and replication breaks: makestep and a host-time-sync agent. A scheduled report fires twice on the night clocks go back in a local-timezone cron; the same job in UTC fires once. PostgreSQL sorting differs between two servers: different collations (LC_COLLATE), a locale mismatch, not a data problem. In Laravel set config/app.php timezone to UTC and format for the user in the view.
| Topic | Do |
|---|---|
| Server timezone | UTC |
| NTP | chrony (or systemd-timesyncd for simple hosts); at least three sources; monitor offset |
| Containers | They share the host clock; a timezone inside an image affects only formatting |
| Application | Store and compute in UTC (Go time.Time with UTC(), Laravel Carbon UTC), convert at the edge |
| Locale | One explicit LANG per host and per database; avoid changing collation later |
| Cron or timers | Document the timezone; timers accept OnCalendar=... UTC suffixes |
Fix: UTC everywhere on servers; chrony enabled and monitored; one locale policy; alert when chronyc tracking offset exceeds a threshold. Time in TLS and tokens is in TLS in Practice and JWT Deep Dive.
Mechanics
From power-on to your service
boot of a systemd distribution, in order
1 firmware (UEFI) loads the boot loader (GRUB, systemd-boot) from the EFI system partition
2 the boot loader loads the kernel and an initramfs (a tiny root filesystem with drivers)
3 the kernel starts, mounts the initramfs, finds the real root (root=UUID=...), switches to it
4 the kernel starts PID 1: /sbin/init -> systemd
5 systemd reads default.target (usually multi-user.target or graphical.target) and walks its dependencies
6 it mounts everything in /etc/fstab, starts sysinit.target (udev, journald, tmpfiles, sysusers), then basic.target
7 network-online.target is reached; sockets and timers are listening; multi-user.target pulls orders-api.service
8 systemd-analyze blame / critical-chain show which units took the timeStarting a service: the system calls behind systemctl start
what systemd does between "start" and your main()
1 create the unit's cgroup /sys/fs/cgroup/system.slice/orders-api.service and write limits (memory.max ...)
2 mkdir StateDirectory= RuntimeDirectory= with the right owner (in systemd, before dropping privileges)
3 clone() a child; in the child: join the cgroup, set up mount/PID/IPC namespaces for the sandbox
4 setrlimit() for LimitNOFILE; setgroups/setgid/setuid to orders (exit 216/217 if this fails)
5 prctl(PR_SET_NO_NEW_PRIVS), install the seccomp filter (SystemCallFilter=), drop capabilities
6 chdir WorkingDirectory= (exit 200 on failure); open stdin/stdout/stderr -> /dev/null and the journal
7 execve(ExecStart=...) (exit 203 on failure); LISTEN_PID, LISTEN_FDS, NOTIFY_SOCKET, JOURNAL_STREAM in the environmentThe status codes in steps 4 to 7 are documented in systemd.exec(5): 200 EXIT_CHDIR, 203 EXIT_EXEC ("the actual process execution failed (specifically, the execve(2) system call). Most likely this is caused by a missing or non-accessible executable file"), 216 EXIT_GROUP, 217 EXIT_USER ("Failed to determine or change user credentials"), 226 EXIT_NAMESPACE, 233 EXIT_RUNTIME_DIRECTORY, 238 EXIT_STATE_DIRECTORY. They appear in systemctl status as status=203/EXEC: the process never reached your code.
The permission check, written as code
The kernel's decision is short enough to write down. The repository's perms.Check follows the same order (owner class, else group class, else other class) and its tests include the case that surprises people: the owner is denied when the owner bits forbid the access, even if the group and others may do it.
Knobs
| Knob | Where | Default and effect |
|---|---|---|
vm.swappiness | sysctl, /proc/sys/vm/swappiness | 60; 0 to 200; higher swaps anonymous pages more readily |
vm.overcommit_memory | sysctl | 0 heuristic; 1 always allow; 2 never overcommit (with vm.overcommit_ratio) |
oom_score_adj | /proc/<pid>/oom_score_adj, OOMScoreAdjust= | -1000 never kill .. +1000 kill first |
fs.file-max, fs.nr_open | sysctl | System-wide and per-process descriptor ceilings |
kernel.pid_max | sysctl | Highest PID; a zombie leak exhausts it |
net.core.somaxconn | sysctl | Ceiling of the listen backlog |
LimitNOFILE=, TasksMax=, MemoryMax= | unit | Per-service limits; cgroup v2 files memory.max, pids.max |
DefaultTimeoutStopSec= | /etc/systemd/system.conf | Stop timeout for units without their own |
SystemMaxUse= | journald.conf | Upper bound of the journal |
UMask= | unit | Umask of the service's processes |
Storage= | journald.conf | volatile, persistent, auto, none |
Error messages you will actually see
| Message | Meaning | First move |
|---|---|---|
Permission denied | EACCES: a mode, ACL, capability, SELinux or AppArmor refused it | namei -l path, id, ls -ld each directory; then ausearch -m avc or dmesg |
Operation not permitted | EPERM: you lack a privilege (chown, binding a low port, setrlimit) | Capabilities, root, NoNewPrivileges |
No such file or directory on a script that exists | The interpreter in the shebang is missing (often CRLF line endings, or #!/bin/bash on Alpine) | head -1 file | od -c, file script |
Text file busy | ETXTBSY: writing to a binary that is running | Write a new file and mv it over (atomic) |
Address already in use | Another process (or a TIME-WAIT quirk) owns the port | ss -ltnp 'sport = :8080' |
Too many open files | EMFILE (process) or ENFILE (system) | /proc/<pid>/limits, LimitNOFILE=, find the leak |
fork: retry: Resource temporarily unavailable | EAGAIN: process or task limit, or zombies | ulimit -u, TasksMax=, ps -eo stat | grep -c Z |
Cannot allocate memory | ENOMEM: commit limit or cgroup limit | free, vm.overcommit_memory, MemoryMax |
No space left on device | ENOSPC: blocks or inodes exhausted (or quota) | df -h, df -i, lsof +L1 |
Read-only file system | EROFS: mounted read-only or sandboxed (ProtectSystem) | findmnt -o TARGET,OPTIONS, ReadWritePaths= |
Failed to start ...: Start request repeated too quickly | The start limit tripped | systemctl reset-failed, fix the crash, journalctl -u |
status=203/EXEC | systemd could not execve the binary | Path, execute bit, noexec mount, wrong architecture |
status=217/USER | The User= does not exist | getent passwd, sysusers |
exit status 137 / 143 | SIGKILL / SIGTERM | OOM or timeout / graceful stop requested |
Go
The Go side is a small service built to be supervised: it takes its listening socket from systemd (socket activation) or from ADDR, signals readiness with READY=1 (so Type=notify is honest), pings the watchdog, reloads on SIGHUP, drains on SIGTERM for 8 seconds (below the unit's TimeoutStopSec=15s), and writes logs to stderr without a timestamp when $JOURNAL_STREAM shows the journal is on the other end. Three helper packages parse and explain what a developer reads from the system: procfs (status, loadavg, meminfo, capability masks), perms (octal and symbolic modes, umask, the permission check) and exitcode (how a parent reads a child's end, and why a zombie exists until Wait). Everything is standard library only.
Before
The unit most teams start with (shown earlier in Writing a service unit) runs as root, with an inline secret, Restart=always, no readiness and no sandbox. The program under it usually does not handle SIGTERM either; the Go side of that is OS Processes, Signals & Graceful Shutdown.
After
The application side: socket inheritance and the LISTEN_PID check, sd_notify over a Unix datagram socket, the reload and drain loop.
// Command orders-api is a small HTTP service written for systemd: it takes its
// listening socket from socket activation or from ADDR, tells systemd when it
// is ready (Type=notify), pings the watchdog, reloads on SIGHUP, drains on
// SIGTERM, and logs to stderr so journald owns timestamps and storage.
package main
import (
"context"
"io"
"log/slog"
"net"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
log := newLogger(os.Getenv, os.Stderr)
if err := mainErr(log); err != nil {
log.Error("exiting", "err", err)
os.Exit(1)
}
}
// newLogger drops the timestamp when $JOURNAL_STREAM says stderr goes to the
// journal, which stamps every line itself.
func newLogger(getenv func(string) string, w io.Writer) *slog.Logger {
opts := &slog.HandlerOptions{}
if getenv("JOURNAL_STREAM") != "" {
opts.ReplaceAttr = func(groups []string, a slog.Attr) slog.Attr {
if len(groups) == 0 && a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
}
}
return slog.New(slog.NewTextHandler(w, opts))
}
func mainErr(log *slog.Logger) error {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
ln, err := listener(os.Getenv, os.Getpid())
if err != nil {
return err
}
var wd time.Duration
if us := watchdogInterval(os.Getenv, os.Getpid()); us > 0 {
wd = time.Duration(us) * time.Microsecond
}
a := newApp(log, os.Getenv("CONFIG_FILE"))
log.Info("starting", "addr", ln.Addr().String(), "uid", os.Getuid(), "pid", os.Getpid())
return run(ctx, ln, a, newNotifier(os.Getenv("NOTIFY_SOCKET")), wd)
}
// listener prefers a socket passed by systemd and falls back to $ADDR.
func listener(getenv func(string) string, pid int) (net.Listener, error) {
n, err := listenFDs(getenv, pid)
if err != nil {
return nil, err
}
if n > 0 {
return inheritListener(firstInheritedFD)
}
addr := getenv("ADDR")
if addr == "" {
addr = "127.0.0.1:8080"
}
return net.Listen("tcp", addr)
}package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
)
const shutdownTimeout = 8 * time.Second
// app holds the state a SIGHUP reloads: one greeting line read from a file.
type app struct {
log *slog.Logger
cfgPath string
mu sync.RWMutex
greeting string
reloads atomic.Int64
ready atomic.Bool // readiness for load balancers; flipped off first on shutdown
}
func newApp(log *slog.Logger, cfgPath string) *app {
a := &app{log: log, cfgPath: cfgPath, greeting: "hello"}
a.ready.Store(true)
a.reload()
a.reloads.Store(0)
return a
}
// reload re-reads the config file. A missing or unreadable file keeps the
// previous value: a reload must never take a running service down.
func (a *app) reload() {
if a.cfgPath == "" {
return
}
b, err := os.ReadFile(a.cfgPath)
if err != nil {
a.log.Warn("reload: keeping previous config", "path", a.cfgPath, "err", err)
return
}
a.mu.Lock()
a.greeting = strings.TrimSpace(string(b))
a.mu.Unlock()
a.reloads.Add(1)
a.log.Info("reloaded config", "path", a.cfgPath)
}
func (a *app) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintln(w, "ok")
})
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) {
if !a.ready.Load() {
http.Error(w, "shutting down", http.StatusServiceUnavailable)
return
}
fmt.Fprintln(w, "ready")
})
mux.HandleFunc("GET /hello", func(w http.ResponseWriter, _ *http.Request) {
a.mu.RLock()
defer a.mu.RUnlock()
fmt.Fprintln(w, a.greeting)
})
mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "{\"id\":%q,\"uid\":%d,\"pid\":%d}\n", r.PathValue("id"), os.Getuid(), os.Getpid())
})
return mux
}
// run serves on ln until ctx is cancelled, then drains for at most
// shutdownTimeout. SIGHUP reloads the config; READY=1 / STOPPING=1 tell systemd
// where the service is in its life.
func run(ctx context.Context, ln net.Listener, a *app, n notifier, wdEvery time.Duration) error {
srv := &http.Server{Handler: a.routes(), ReadHeaderTimeout: 5 * time.Second}
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
hup := make(chan os.Signal, 1)
signal.Notify(hup, syscall.SIGHUP)
defer signal.Stop(hup)
if err := n.Notify("READY=1\nSTATUS=serving on " + ln.Addr().String()); err != nil {
a.log.Warn("notify READY", "err", err)
}
var tick <-chan time.Time
if wdEvery > 0 {
t := time.NewTicker(wdEvery)
defer t.Stop()
tick = t.C
}
for {
select {
case <-hup:
a.reload()
case <-tick:
_ = n.Notify("WATCHDOG=1")
case err := <-errc:
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
case <-ctx.Done():
a.ready.Store(false) // /readyz answers 503 from here on, then the drain starts
_ = n.Notify("STOPPING=1\nSTATUS=draining")
sctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
if err := srv.Shutdown(sctx); err != nil {
return fmt.Errorf("shutdown: %w", err)
}
return nil
}
}
}package main
import (
"errors"
"fmt"
"net"
"os"
"strconv"
)
// firstInheritedFD is SD_LISTEN_FDS_START: sockets passed by systemd start at
// file descriptor 3 (0, 1 and 2 are stdin, stdout and stderr).
const firstInheritedFD = 3
// listenFDs implements the check from sd_listen_fds(3): $LISTEN_PID must name
// this process, otherwise the variables were meant for a parent or a sibling.
func listenFDs(getenv func(string) string, pid int) (int, error) {
p := getenv("LISTEN_PID")
if p == "" {
return 0, nil
}
if p != strconv.Itoa(pid) {
return 0, nil
}
n, err := strconv.Atoi(getenv("LISTEN_FDS"))
if err != nil {
return 0, fmt.Errorf("LISTEN_FDS: %w", err)
}
if n < 0 {
return 0, errors.New("LISTEN_FDS is negative")
}
return n, nil
}
// inheritListener turns descriptor fd into a net.Listener. The descriptor is
// duplicated by net.FileListener and the original is closed.
func inheritListener(fd int) (net.Listener, error) {
f := os.NewFile(uintptr(fd), "systemd-socket")
if f == nil {
return nil, errors.New("invalid inherited descriptor")
}
defer f.Close()
return net.FileListener(f)
}package main
import (
"errors"
"fmt"
"net"
"strings"
)
// notifier sends sd_notify(3) messages. With no NOTIFY_SOCKET (a service
// started by hand, not by systemd) it does nothing, so the same binary runs
// everywhere.
type notifier interface {
Notify(state string) error
}
type nopNotifier struct{}
func (nopNotifier) Notify(string) error { return nil }
type socketNotifier struct{ path string }
// newNotifier builds a notifier from the value of $NOTIFY_SOCKET.
func newNotifier(sock string) notifier {
if sock == "" {
return nopNotifier{}
}
return socketNotifier{path: sock}
}
// Notify sends one datagram whose payload is the state string, for example
// "READY=1" or "STATUS=draining". A leading "@" means a Linux abstract-namespace
// socket, which the Go net package spells with a leading NUL byte.
func (n socketNotifier) Notify(state string) error {
if n.path == "" {
return errors.New("empty notify socket")
}
name := n.path
if strings.HasPrefix(name, "@") {
name = "\x00" + name[1:]
}
conn, err := net.DialUnix("unixgram", nil, &net.UnixAddr{Name: name, Net: "unixgram"})
if err != nil {
return fmt.Errorf("dial notify socket: %w", err)
}
defer conn.Close()
if _, err := conn.Write([]byte(state)); err != nil {
return fmt.Errorf("write notify datagram: %w", err)
}
return nil
}
// watchdogInterval returns half of WATCHDOG_USEC, the ping period systemd
// recommends, or 0 when the watchdog is not armed for this process.
func watchdogInterval(getenv func(string) string, pid int) (usec int64) {
v := getenv("WATCHDOG_USEC")
if v == "" {
return 0
}
if p := getenv("WATCHDOG_PID"); p != "" && p != fmt.Sprint(pid) {
return 0
}
if _, err := fmt.Sscan(v, &usec); err != nil || usec <= 0 {
return 0
}
return usec / 2
}The tests stand in for systemd: a Unix datagram socket plays $NOTIFY_SOCKET and records READY=1, WATCHDOG=1 and STOPPING=1; a duplicated descriptor plays fd 3; the process sends itself SIGHUP and checks that the config was re-read without a restart.
package main
import (
"context"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"syscall"
"testing"
"time"
)
func quiet() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
func env(m map[string]string) func(string) string { return func(k string) string { return m[k] } }
func TestListenFDs(t *testing.T) {
cases := []struct {
name string
env map[string]string
pid int
want int
err bool
}{
{"not socket activated", map[string]string{}, 10, 0, false},
{"meant for another pid", map[string]string{"LISTEN_PID": "99", "LISTEN_FDS": "1"}, 10, 0, false},
{"one socket", map[string]string{"LISTEN_PID": "10", "LISTEN_FDS": "1"}, 10, 1, false},
{"two sockets", map[string]string{"LISTEN_PID": "10", "LISTEN_FDS": "2"}, 10, 2, false},
{"garbage count", map[string]string{"LISTEN_PID": "10", "LISTEN_FDS": "x"}, 10, 0, true},
}
for _, c := range cases {
got, err := listenFDs(env(c.env), c.pid)
if got != c.want || (err != nil) != c.err {
t.Errorf("%s: got (%d, %v), want (%d, err=%v)", c.name, got, err, c.want, c.err)
}
}
}
func TestInheritListener(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
f, err := ln.(*net.TCPListener).File()
if err != nil {
t.Fatal(err)
}
defer f.Close()
// systemd hands the service a descriptor; dup one to play that role.
fd, err := syscall.Dup(int(f.Fd()))
if err != nil {
t.Fatal(err)
}
got, err := inheritListener(fd)
if err != nil {
t.Fatal(err)
}
defer got.Close()
if got.Addr().String() != ln.Addr().String() {
t.Fatalf("inherited %s, want %s", got.Addr(), ln.Addr())
}
}
// recorder listens on a unixgram socket like systemd's NOTIFY_SOCKET.
type recorder struct {
mu sync.Mutex
msgs []string
}
func (r *recorder) all() []string {
r.mu.Lock()
defer r.mu.Unlock()
return append([]string(nil), r.msgs...)
}
func startRecorder(t *testing.T) (*recorder, string) {
t.Helper()
dir, err := os.MkdirTemp("/tmp", "n")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(dir) })
path := dir + "/notify"
pc, err := net.ListenPacket("unixgram", path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { pc.Close() })
r := &recorder{}
go func() {
buf := make([]byte, 1024)
for {
n, _, err := pc.ReadFrom(buf)
if err != nil {
return
}
r.mu.Lock()
r.msgs = append(r.msgs, string(buf[:n]))
r.mu.Unlock()
}
}()
return r, path
}
func waitFor(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
if cond() {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("timed out waiting for %s", what)
}
func TestNotifierSendsDatagram(t *testing.T) {
r, path := startRecorder(t)
if err := newNotifier(path).Notify("READY=1"); err != nil {
t.Fatal(err)
}
waitFor(t, "READY=1", func() bool { return len(r.all()) == 1 })
if got := r.all()[0]; got != "READY=1" {
t.Fatalf("got %q", got)
}
if err := newNotifier("").Notify("READY=1"); err != nil {
t.Fatalf("nop notifier must not fail: %v", err)
}
}
func TestWatchdogInterval(t *testing.T) {
if got := watchdogInterval(env(map[string]string{"WATCHDOG_USEC": "30000000"}), 5); got != 15000000 {
t.Fatalf("got %d, want 15000000", got)
}
if got := watchdogInterval(env(map[string]string{"WATCHDOG_USEC": "30000000", "WATCHDOG_PID": "6"}), 5); got != 0 {
t.Fatalf("other pid: got %d, want 0", got)
}
if got := watchdogInterval(env(nil), 5); got != 0 {
t.Fatalf("unset: got %d, want 0", got)
}
}
func TestRunLifecycle(t *testing.T) {
cfg := t.TempDir() + "/greeting"
if err := os.WriteFile(cfg, []byte("v1\n"), 0o600); err != nil {
t.Fatal(err)
}
r, sock := startRecorder(t)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
a := newApp(quiet(), cfg)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- run(ctx, ln, a, newNotifier(sock), 20*time.Millisecond) }()
get := func(path string) string {
resp, err := http.Get("http://" + ln.Addr().String() + path)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return strings.TrimSpace(string(b))
}
if got := get("/hello"); got != "v1" {
t.Fatalf("/hello = %q, want v1", got)
}
if got := get("/healthz"); got != "ok" {
t.Fatalf("/healthz = %q", got)
}
// SIGHUP re-reads the file without restarting.
if err := os.WriteFile(cfg, []byte("v2\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := syscall.Kill(os.Getpid(), syscall.SIGHUP); err != nil {
t.Fatal(err)
}
waitFor(t, "reload", func() bool { return get("/hello") == "v2" })
waitFor(t, "watchdog ping", func() bool {
for _, m := range r.all() {
if m == "WATCHDOG=1" {
return true
}
}
return false
})
cancel()
select {
case err := <-done:
if err != nil {
t.Fatalf("run returned %v", err)
}
case <-time.After(3 * time.Second):
t.Fatal("run did not return after cancel")
}
var ready, stopping, wd bool
for _, m := range r.all() {
ready = ready || strings.HasPrefix(m, "READY=1")
stopping = stopping || strings.HasPrefix(m, "STOPPING=1")
wd = wd || m == "WATCHDOG=1"
}
if !ready || !stopping || !wd {
t.Fatalf("notify messages missing: ready=%v stopping=%v watchdog=%v (%q)", ready, stopping, wd, r.all())
}
}
func TestReloadKeepsOldValueOnError(t *testing.T) {
cfg := t.TempDir() + "/greeting"
if err := os.WriteFile(cfg, []byte("keep"), 0o600); err != nil {
t.Fatal(err)
}
a := newApp(quiet(), cfg)
if err := os.Remove(cfg); err != nil {
t.Fatal(err)
}
a.reload()
if a.greeting != "keep" {
t.Fatalf("greeting = %q after failed reload, want keep", a.greeting)
}
}
func TestLoggerDropsTimeUnderJournal(t *testing.T) {
var withJournal, without strings.Builder
newLogger(env(map[string]string{"JOURNAL_STREAM": "8:12345"}), &withJournal).Info("x")
newLogger(env(nil), &without).Info("x")
if strings.Contains(withJournal.String(), "time=") {
t.Errorf("journal logger kept the timestamp: %q", withJournal.String())
}
if !strings.Contains(without.String(), "time=") {
t.Errorf("plain logger lost the timestamp: %q", without.String())
}
}
func TestReadyzFlipsOffOnShutdown(t *testing.T) {
a := newApp(quiet(), "")
rec := func() int {
w := httptest.NewRecorder()
a.routes().ServeHTTP(w, httptest.NewRequest("GET", "/readyz", nil))
return w.Code
}
if got := rec(); got != 200 {
t.Fatalf("/readyz before shutdown = %d, want 200", got)
}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- run(ctx, ln, a, newNotifier(""), 0) }()
waitFor(t, "server up", func() bool {
r, err := http.Get("http://" + ln.Addr().String() + "/readyz")
if err != nil {
return false
}
r.Body.Close()
return r.StatusCode == 200
})
cancel()
if err := <-done; err != nil {
t.Fatal(err)
}
if got := rec(); got != 503 {
t.Fatalf("/readyz after shutdown began = %d, want 503", got)
}
}Reading the system from Go: /proc formats, permissions, exit statuses.
// Package procfs parses the text formats of /proc that a developer reads daily:
// /proc/PID/status, /proc/loadavg, /proc/meminfo and the capability masks. The
// parsers take an io.Reader so they run (and are tested) on any OS; only
// reading the real files needs Linux.
package procfs
import (
"bufio"
"fmt"
"io"
"math/bits"
"strconv"
"strings"
)
// Status is the subset of /proc/PID/status (proc_pid_status(5)) used here.
type Status struct {
Name string
State string // letter, for example "S"
PPid int
Uid [4]int // real, effective, saved set-user-ID, filesystem
Gid [4]int
VmRSSkB int64
Threads int
CapEff uint64
NoNewPr bool
}
// ParseStatus reads "Key:\tvalue" lines.
func ParseStatus(r io.Reader) (Status, error) {
var s Status
sc := bufio.NewScanner(r)
for sc.Scan() {
k, v, ok := strings.Cut(sc.Text(), ":")
if !ok {
continue
}
v = strings.TrimSpace(v)
var err error
switch k {
case "Name":
s.Name = v
case "State":
s.State, _, _ = strings.Cut(v, " ")
case "PPid":
s.PPid, err = strconv.Atoi(v)
case "Uid":
s.Uid, err = four(v)
case "Gid":
s.Gid, err = four(v)
case "VmRSS":
s.VmRSSkB, err = kB(v)
case "Threads":
s.Threads, err = strconv.Atoi(v)
case "CapEff":
s.CapEff, err = strconv.ParseUint(v, 16, 64)
case "NoNewPrivs":
s.NoNewPr = v == "1"
}
if err != nil {
return Status{}, fmt.Errorf("field %s: %w", k, err)
}
}
return s, sc.Err()
}
func four(v string) ([4]int, error) {
var out [4]int
f := strings.Fields(v)
if len(f) != 4 {
return out, fmt.Errorf("want 4 ids, got %d", len(f))
}
for i, x := range f {
n, err := strconv.Atoi(x)
if err != nil {
return out, err
}
out[i] = n
}
return out, nil
}
func kB(v string) (int64, error) {
num, unit, _ := strings.Cut(v, " ")
if unit != "" && unit != "kB" {
return 0, fmt.Errorf("unexpected unit %q", unit)
}
return strconv.ParseInt(num, 10, 64)
}
// StateName spells the one-letter process states of ps(1) / proc(5).
func StateName(letter string) string {
switch letter {
case "R":
return "running or runnable"
case "S":
return "interruptible sleep"
case "D":
return "uninterruptible sleep (usually disk I/O)"
case "T", "t":
return "stopped (signal or tracer)"
case "Z":
return "zombie (exited, not yet reaped)"
case "I":
return "idle kernel thread"
default:
return "other"
}
}
// Load is /proc/loadavg: three averages, runnable/total scheduling entities, last PID.
type Load struct {
One, Five, Fifteen float64
Running, Total int
LastPID int
}
// ParseLoadavg parses "0.52 0.41 0.30 2/312 4821".
func ParseLoadavg(line string) (Load, error) {
f := strings.Fields(line)
if len(f) < 5 {
return Load{}, fmt.Errorf("loadavg: want 5 fields, got %d", len(f))
}
var l Load
var err error
for i, dst := range []*float64{&l.One, &l.Five, &l.Fifteen} {
if *dst, err = strconv.ParseFloat(f[i], 64); err != nil {
return Load{}, err
}
}
run, tot, ok := strings.Cut(f[3], "/")
if !ok {
return Load{}, fmt.Errorf("loadavg: bad entities field %q", f[3])
}
if l.Running, err = strconv.Atoi(run); err != nil {
return Load{}, err
}
if l.Total, err = strconv.Atoi(tot); err != nil {
return Load{}, err
}
l.LastPID, err = strconv.Atoi(f[4])
return l, err
}
// PerCPU divides the one-minute average by the CPU count: a value above 1
// means more runnable (and, on Linux, uninterruptible) tasks than CPUs.
func (l Load) PerCPU(cpus int) float64 { return l.One / float64(cpus) }
// ParseMeminfo returns /proc/meminfo as kB values keyed by field name.
func ParseMeminfo(r io.Reader) (map[string]int64, error) {
out := map[string]int64{}
sc := bufio.NewScanner(r)
for sc.Scan() {
k, v, ok := strings.Cut(sc.Text(), ":")
if !ok {
continue
}
n, err := kB(strings.TrimSpace(v))
if err != nil {
return nil, fmt.Errorf("%s: %w", k, err)
}
out[k] = n
}
return out, sc.Err()
}
// Pressure reports what `free` calls "available" as a percentage of total:
// the number to alert on, not MemFree.
func Pressure(m map[string]int64) (availablePct float64, err error) {
total, ok1 := m["MemTotal"]
avail, ok2 := m["MemAvailable"]
if !ok1 || !ok2 || total == 0 {
return 0, fmt.Errorf("meminfo lacks MemTotal/MemAvailable")
}
return 100 * float64(avail) / float64(total), nil
}
// capNames follows include/uapi/linux/capability.h (saved in pipeline/sources).
var capNames = []string{
"CAP_CHOWN", "CAP_DAC_OVERRIDE", "CAP_DAC_READ_SEARCH", "CAP_FOWNER", "CAP_FSETID",
"CAP_KILL", "CAP_SETGID", "CAP_SETUID", "CAP_SETPCAP", "CAP_LINUX_IMMUTABLE",
"CAP_NET_BIND_SERVICE", "CAP_NET_BROADCAST", "CAP_NET_ADMIN", "CAP_NET_RAW", "CAP_IPC_LOCK",
"CAP_IPC_OWNER", "CAP_SYS_MODULE", "CAP_SYS_RAWIO", "CAP_SYS_CHROOT", "CAP_SYS_PTRACE",
"CAP_SYS_PACCT", "CAP_SYS_ADMIN", "CAP_SYS_BOOT", "CAP_SYS_NICE", "CAP_SYS_RESOURCE",
"CAP_SYS_TIME", "CAP_SYS_TTY_CONFIG", "CAP_MKNOD", "CAP_LEASE", "CAP_AUDIT_WRITE",
"CAP_AUDIT_CONTROL", "CAP_SETFCAP",
}
// DecodeCaps names the first 32 capability bits set in mask (the later ones are
// printed as CAP_<n>). `capsh --decode=<mask>` does the same on a real host.
func DecodeCaps(mask uint64) []string {
var out []string
for m := mask; m != 0; {
i := bits.TrailingZeros64(m)
m &^= 1 << uint(i)
if i < len(capNames) {
out = append(out, capNames[i])
} else {
out = append(out, "CAP_"+strconv.Itoa(i))
}
}
return out
}// Package perms models the Unix permission check the kernel performs on every
// open(2): owner, then group, then other; with umask, octal and the special
// bits. It is a teaching model: no ACLs, no capabilities, no LSMs.
package perms
import (
"io/fs"
"strconv"
)
// Octal renders the permission and special bits the way chmod(1) takes them:
// 0644, 0755, 4755 (setuid), 2775 (setgid), 1777 (sticky).
func Octal(m fs.FileMode) string {
v := uint32(m.Perm())
if m&fs.ModeSetuid != 0 {
v |= 04000
}
if m&fs.ModeSetgid != 0 {
v |= 02000
}
if m&fs.ModeSticky != 0 {
v |= 01000
}
s := strconv.FormatUint(uint64(v), 8)
for len(s) < 4 {
s = "0" + s
}
return s
}
// FromOctal is the inverse of Octal.
func FromOctal(s string) (fs.FileMode, error) {
v, err := strconv.ParseUint(s, 8, 32)
if err != nil {
return 0, err
}
m := fs.FileMode(v & 0o777)
if v&0o4000 != 0 {
m |= fs.ModeSetuid
}
if v&0o2000 != 0 {
m |= fs.ModeSetgid
}
if v&0o1000 != 0 {
m |= fs.ModeSticky
}
return m, nil
}
// Symbolic renders the nine rwx characters as ls -l does, with s/S, t/T for
// the special bits (lowercase when the execute bit underneath is also set).
func Symbolic(m fs.FileMode) string {
const rwx = "rwxrwxrwx"
b := []byte(rwx)
for i := 0; i < 9; i++ {
if m.Perm()&(1<<uint(8-i)) == 0 {
b[i] = '-'
}
}
special := func(on bool, idx int, lower, upper byte) {
if !on {
return
}
if b[idx] == 'x' {
b[idx] = lower
} else {
b[idx] = upper
}
}
special(m&fs.ModeSetuid != 0, 2, 's', 'S')
special(m&fs.ModeSetgid != 0, 5, 's', 'S')
special(m&fs.ModeSticky != 0, 8, 't', 'T')
return string(b)
}
// ApplyUmask is what open(2)/mkdir(2) do with the requested mode: the umask
// bits are removed (mode & ~umask).
func ApplyUmask(requested, umask fs.FileMode) fs.FileMode {
return requested &^ (umask & 0o777)
}
// Access bits for Check.
const (
Read = 4
Write = 2
Execute = 1
)
// Check answers "may uid (with supplementary groups gids) do want on a file
// owned by ownerUID:ownerGID with mode m?". Only one class applies: if you are
// the owner the group and other bits are never consulted, even when they would
// allow more. uid 0 is not modelled here (root bypasses the read/write bits;
// execute still needs at least one x bit on a regular file).
func Check(m fs.FileMode, ownerUID, ownerGID, uid int, gids []int, want int) bool {
p := int(m.Perm())
var class int
switch {
case uid == ownerUID:
class = p >> 6 & 7
case inGroup(ownerGID, gids):
class = p >> 3 & 7
default:
class = p & 7
}
return class&want == want
}
func inGroup(gid int, gids []int) bool {
for _, g := range gids {
if g == gid {
return true
}
}
return false
}// Package exitcode shows how a parent learns how a child ended: a normal exit
// status, or death by signal (which a shell reports as 128 + signal number).
package exitcode
import (
"errors"
"fmt"
"os/exec"
"syscall"
)
// Result is what wait(2) reports.
type Result struct {
Exited bool
Code int // valid when Exited
Signaled bool
Signal syscall.Signal // valid when Signaled
}
// ShellStatus is the number `$?` holds in a POSIX shell.
func (r Result) ShellStatus() int {
if r.Signaled {
return 128 + int(r.Signal)
}
return r.Code
}
// String is a one-line explanation for logs.
func (r Result) String() string {
if r.Signaled {
return fmt.Sprintf("killed by signal %d (%s), shell status %d", int(r.Signal), r.Signal, r.ShellStatus())
}
return fmt.Sprintf("exited with status %d", r.Code)
}
// Of inspects the error returned by (*exec.Cmd).Wait or Run. A nil error is a
// clean exit 0; anything that is not an *exec.ExitError (the binary was not
// found, no permission) is returned as is: that is a failure to start, not an
// exit status.
func Of(err error) (Result, error) {
if err == nil {
return Result{Exited: true}, nil
}
var ee *exec.ExitError
if !errors.As(err, &ee) {
return Result{}, err
}
ws, ok := ee.Sys().(syscall.WaitStatus)
if !ok {
return Result{Exited: true, Code: ee.ExitCode()}, nil
}
if ws.Signaled() {
return Result{Signaled: true, Signal: ws.Signal()}, nil
}
return Result{Exited: true, Code: ws.ExitStatus()}, nil
}package exitcode
import (
"os/exec"
"strconv"
"strings"
"syscall"
"testing"
"time"
)
func TestOf(t *testing.T) {
cases := []struct {
name string
script string
wantShell int
wantSignal syscall.Signal
}{
{"success", "exit 0", 0, 0},
{"failure", "exit 3", 3, 0},
{"not found by the shell", "nonexistent-cmd-xyz 2>/dev/null", 127, 0},
{"SIGTERM", "kill -TERM $$", 128 + 15, syscall.SIGTERM},
{"SIGKILL", "kill -KILL $$", 128 + 9, syscall.SIGKILL},
}
for _, c := range cases {
r, err := Of(exec.Command("sh", "-c", c.script).Run())
if err != nil {
t.Fatalf("%s: %v", c.name, err)
}
if r.ShellStatus() != c.wantShell || r.Signal != c.wantSignal {
t.Errorf("%s: %s (signal %v)", c.name, r, r.Signal)
}
}
}
func TestStartFailureIsNotAnExitStatus(t *testing.T) {
_, err := Of(exec.Command("/nonexistent/binary").Run())
if err == nil {
t.Fatal("a command that cannot start must return an error, not a Result")
}
}
func TestString(t *testing.T) {
r, _ := Of(exec.Command("sh", "-c", "kill -TERM $$").Run())
if s := r.String(); !strings.Contains(s, "terminated") && !strings.Contains(s, "signal 15") {
t.Fatalf("String() = %q", s)
}
}
// zombieState polls ps for the process state letter.
func zombieState(pid int) string {
out, _ := exec.Command("ps", "-o", "stat=", "-p", strconv.Itoa(pid)).Output()
return strings.TrimSpace(string(out))
}
// A child that has exited but has not been waited for stays in the process
// table as a zombie ("Z"); Wait reaps it and the entry disappears.
func TestZombieUntilWait(t *testing.T) {
cmd := exec.Command("sh", "-c", "exit 0")
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
pid := cmd.Process.Pid
deadline := time.Now().Add(3 * time.Second)
var st string
for time.Now().Before(deadline) {
if st = zombieState(pid); strings.HasPrefix(st, "Z") {
break
}
time.Sleep(20 * time.Millisecond)
}
if !strings.HasPrefix(st, "Z") {
t.Fatalf("child state before Wait = %q, want Z", st)
}
if err := cmd.Wait(); err != nil {
t.Fatal(err)
}
if st := zombieState(pid); st != "" {
t.Fatalf("after Wait the entry should be gone, ps says %q", st)
}
}module academy/linux-for-developers
go 1.24The deployment around the binary: the system user and directories, an atomic release switch with rollback, and the unit with its optional socket. Together they are the service user for a Go binary and deploying a Go binary as a systemd service.
#!/bin/sh
# provision-service-user.sh: create the system user and directories for a Go service. Idempotent; run as root.
# usage: provision-service-user.sh orders-api orders
set -eu
svc=${1:?service name, e.g. orders-api}
user=${2:?user name, e.g. orders}
# A system account: low UID range, no password, no login shell, home is its state directory.
if ! getent passwd "$user" >/dev/null; then
useradd --system --user-group --home-dir "/var/lib/$svc" --no-create-home \
--shell /usr/sbin/nologin --comment "$svc service" "$user"
fi
# Release directory owned by root: the service can execute its binary but never overwrite it.
install -d -m 0755 -o root -g root "/opt/$svc" "/opt/$svc/releases"
# Config readable by the service, writable only by root.
install -d -m 0750 -o root -g "$user" "/etc/$svc"
# State directory writable by the service (the unit's StateDirectory= would also create it).
install -d -m 0750 -o "$user" -g "$user" "/var/lib/$svc"
id "$user"#!/bin/bash
# deploy-go-binary.sh: install a new build of a Go service next to the old one, switch atomically, roll back on failure.
# usage: deploy-go-binary.sh orders-api ./orders-api-linux-amd64 <sha256>
set -euo pipefail
svc=${1:?service name}
bin=${2:?path to the new binary}
want_sha=${3:?expected sha256 of the binary}
echo "$want_sha $bin" | sha256sum --check --status || { echo "checksum mismatch" >&2; exit 1; }
rel=/opt/$svc/releases/$(date -u +%Y%m%dT%H%M%SZ)-${want_sha:0:12}
install -d -m 0755 "$rel"
install -m 0755 -o root -g root "$bin" "$rel/$svc"
prev=$(readlink -f "/opt/$svc/current" 2>/dev/null || true)
# ln -sfn + mv -T: the symlink is replaced by one rename(2), so "current" always points at a complete release.
ln -sfn "$rel" "/opt/$svc/current.new"
mv -T "/opt/$svc/current.new" "/opt/$svc/current"
if systemctl restart "$svc.service" && systemctl is-active --quiet "$svc.service"; then
echo "deployed $rel"
# keep the five newest releases
ls -1dt /opt/"$svc"/releases/* | tail -n +6 | xargs -r rm -rf
else
echo "start failed, rolling back to ${prev:-none}" >&2
if [ -n "$prev" ]; then
ln -sfn "$prev" "/opt/$svc/current.new" && mv -T "/opt/$svc/current.new" "/opt/$svc/current"
systemctl restart "$svc.service"
fi
journalctl -u "$svc.service" -n 30 --no-pager >&2
exit 1
fi# /etc/systemd/system/orders-api.socket
# Optional socket activation: systemd owns the port, starts orders-api on the first connection and
# hands the descriptor over as fd 3 ($LISTEN_FDS=1, $LISTEN_PID=<pid>); restarts of the service do not refuse connections.
# Enable the socket, not the service: systemctl enable --now orders-api.socket
[Unit]
Description=Orders API listening socket
[Socket]
ListenStream=127.0.0.1:8080
# Binding below 1024 is also possible here without any capability for the service: systemd (root) binds.
Accept=no
[Install]
WantedBy=sockets.target# /etc/orders-api/orders-api.env (owner root:orders, mode 0640)
# EnvironmentFile syntax: KEY=value, one per line. No `export`, no $VAR expansion, no command substitution.
CONFIG_FILE=/etc/orders-api/greeting
DATABASE_URL=postgres://orders@127.0.0.1:5432/orders?sslmode=disable# /etc/sysusers.d/orders.conf (apply: systemd-sysusers)
# Type Name ID "GECOS" Home Shell
u orders - "Orders API service" /var/lib/orders-api /usr/sbin/nologin# /etc/tmpfiles.d/orders.conf (apply: systemd-tmpfiles --create)
# Type Path Mode User Group Age Argument
d /var/backups/orders 0750 orders orders -
d /var/log/php-fpm-shop 0750 www-data adm -
# Delete scratch files older than 7 days in a cache directory that the application never cleans.
d /var/cache/shop-tmp 0750 www-data www-data 7d# /etc/systemd/system/orders-api.service.d/override.conf (created by `systemctl edit orders-api`)
# A drop-in changes or adds settings without copying the whole unit. An empty assignment resets a list setting.
[Service]
LimitNOFILE=131072
MemoryMax=768M
Environment=GOMEMLIMIT=600MiBThe Go angle
- Static binary, one artefact.
CGO_ENABLED=0 go build -trimpath -ldflags "-s -w"produces a file that runs on Debian, RHEL and Alpine alike (no glibc version coupling) and that you copy to/opt/<svc>/releases/<id>/. The images chapter covers the same flags for containers. - Signals.
signal.NotifyContext(ctx, syscall.SIGTERM, syscall.SIGINT)is the stop path;signal.Notify(ch, syscall.SIGHUP)is the reload path.os/signalcannot catch SIGKILL or SIGSTOP (signal(7)). WithType=notifysystemd waits forREADY=1, so a service that fails to bind is reported atsystemctl start, not minutes later. - Socket activation.
net.FileListeneron descriptor 3 (SD_LISTEN_FDS_START) after checkingLISTEN_PID == os.Getpid()is the whole protocol (sd_listen_fds(3)). Benefits: ports below 1024 without a capability, no connection refused during a restart (the kernel queues them), and lazy start. - Environment, not flags, for secrets.
EnvironmentFile=with mode0640 root:orderskeeps secrets out of the unit and out ofpsarguments; a flag value is visible in/proc/<pid>/cmdlineto every local user. See CLI Flags, Environment Variables & Logging. - Logging. Write to stderr; systemd stamps time, unit and priority. The service drops its own timestamp when
$JOURNAL_STREAMis set (systemd.exec(5): the variable "contains the device and inode numbers of the connection file descriptor"; the manual adds that checking only whether it is set is generally not sufficient, since children may inherit it, and the robust test compares those numbers withfstatof stderr; the service here takes the simple check). For a priority per line, prefix the line with thesd-daemon(3)level strings such as<3>(SD_ERR) or use a journald handler; plain lines are stored at priorityinfo. - Memory.
GOMEMLIMITaims to keep Go's memory use under a target by running the GC harder; it is a soft limit (the GC guide: usage may surpass it to avoid GC thrashing, for example when live data alone exceeds it), soMemoryMaxstays the wall behind it.GOMAXPROCSfollows a cgroup CPU limit only from Go 1.25 ("Container-aware GOMAXPROCS" in the release notes); on older versions set it explicitly when you useCPUQuota=. - File descriptors and children. Close response bodies;
Waitfor everyStart(theexitcodetest shows the zombie); remember that exec'd children inherit descriptors without close-on-exec, and that Go sets close-on-exec for the ones it opens. - Health for the supervisor.
WatchdogSec=plusWATCHDOG=1detects a hung process that is still "running";/readyz(503 as soon as shutdown begins, tested) and/healthzare for load balancers, the watchdog is for systemd.
Laravel
Before
Laravel's documentation tells you to add one crontab entry, * * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1, and to keep queue workers alive with Supervisor. That works. What it leaves out is on the Linux side: the output goes to /dev/null (a failing scheduler is invisible), a tick that takes longer than a minute overlaps with the next, workers run under whatever user wrote the crontab, and PHP-FPM shares one pool (and one user) with every other site on the machine.
After
systemd replaces the crontab line, the Supervisor program and the shared pool with units. First, the scheduler as a timer and a one-shot service: logs in the journal, the exit status of each tick, no overlapping ticks, and Nice= so a heavy task does not starve web requests.
# /etc/systemd/system/laravel-schedule.timer
# Replaces the one crontab line Laravel documents: "* * * * * cd /path && php artisan schedule:run >> /dev/null 2>&1".
# Gains: logs in the journal (journalctl -u laravel-schedule), `systemctl list-timers`, no overlap of ticks
# (a timer does not restart its unit while that unit is still active; systemd.timer(5)).
[Unit]
Description=Laravel scheduler (every minute)
[Timer]
OnCalendar=*-*-* *:*:00
# Without this the timer fires within a minute-long window of the second; pin it to the second.
AccuracySec=1s
Persistent=false
[Install]
WantedBy=timers.target# /etc/systemd/system/laravel-schedule.service
# One tick of the Laravel scheduler: `schedule:run` evaluates every task due this minute, starts them and exits.
[Unit]
Description=Laravel scheduler tick (shop)
# Do not run while the app is being deployed.
ConditionPathExists=/var/www/shop/current/artisan
[Service]
Type=oneshot
User=www-data
Group=www-data
WorkingDirectory=/var/www/shop/current
ExecStart=/usr/bin/php artisan schedule:run --no-interaction
# No TimeoutStartSec here: with sub-minute schedules `schedule:run` deliberately keeps running until the end of
# the minute (Laravel docs), and a foreground task may take longer than a minute. Timers do not start a second
# tick while this one is still active. Dispatch heavy work as queued jobs so a tick stays short.
# Default KillMode=control-group would kill any child that outlives `schedule:run` (e.g. runInBackground()).
# KillMode=process would let such children live on, but outside systemd's supervision and limits: prefer queued jobs.
Nice=5
PrivateTmp=yes
ProtectHome=yesThe queue workers as a template unit: laravel-queue@1, @2, @3 are three workers. queue:work --max-time=3600 makes each worker exit after an hour so that memory and stale code do not accumulate, and Restart=always starts a fresh one; Laravel's queue documentation recommends exactly that combination with a process monitor, and states that when a worker "receives a termination signal such as SIGQUIT, SIGTERM, or SIGINT while processing a job, the worker will finish its current job before exiting", so TimeoutStopSec must cover your longest job.
# /etc/systemd/system/laravel-queue@.service
# A template unit: `systemctl enable --now laravel-queue@1 laravel-queue@2` starts two workers; %i is the instance name.
[Unit]
Description=Laravel queue worker %i (shop)
After=network-online.target redis-server.service
Wants=network-online.target
[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/var/www/shop/current
# --max-time makes the worker exit after an hour so memory leaks and stale code do not accumulate;
# Restart=always starts a fresh one. --tries and --sleep are the usual knobs.
ExecStart=/usr/bin/php artisan queue:work redis --sleep=3 --tries=3 --max-time=3600
Restart=always
RestartSec=3
# SIGTERM (the default stop signal) lets the worker finish the job it is running. Give long jobs time.
KillSignal=SIGTERM
TimeoutStopSec=120
MemoryMax=512M
PrivateTmp=yes
ProtectHome=yes
[Install]
WantedBy=multi-user.targetThe PHP-FPM pool as a systemd unit: a dedicated master, its own php-fpm.conf and pool, a Unix socket under /run, graceful reload on SIGUSR2, graceful stop on SIGQUIT (php-fpm(8): SIGQUIT "graceful stop", SIGUSR2 "graceful reload of all workers + reload of fpm conf/binary", SIGINT/SIGTERM "immediate termination").
# /etc/systemd/system/php-fpm-shop.service
# A dedicated PHP-FPM master for one application (own pools, own user, own limits), next to the distribution's php-fpm.
# Binary name and paths follow Debian/Ubuntu packages (php8.4-fpm); on RHEL/Fedora it is /usr/sbin/php-fpm.
[Unit]
Description=PHP-FPM for shop
After=network.target
[Service]
# Type=notify works when PHP was built with systemd support (the distribution packages are);
# FPM then reports readiness and a status line (see systemd_interval in php-fpm.conf).
Type=notify
ExecStart=/usr/sbin/php-fpm8.4 --nodaemonize --fpm-config /etc/php-fpm-shop/php-fpm.conf
# SIGUSR2 = graceful reload of the master: new workers with new code/config, old ones finish their request.
ExecReload=/bin/kill -USR2 $MAINPID
# SIGQUIT = graceful stop of FPM (finish requests); SIGTERM = fast stop.
KillSignal=SIGQUIT
TimeoutStopSec=30
RuntimeDirectory=php-fpm-shop
PrivateTmp=yes
ProtectSystem=full
ProtectHome=yes
NoNewPrivileges=yes
# FPM workers open many files (uploads, sessions, vendor/). Raise from the default.
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target; /etc/php-fpm-shop/php-fpm.conf (global section + one pool; ";" starts a comment)
[global]
pid = /run/php-fpm-shop/php-fpm.pid
error_log = syslog
; systemd supervises the master, so FPM must stay in the foreground (the unit also passes --nodaemonize).
daemonize = no
; Seconds between health reports to systemd when Type=notify.
systemd_interval = 10
; Restart the master if this many children die from SIGSEGV or SIGBUS within the interval.
emergency_restart_threshold = 10
emergency_restart_interval = 1m
process_control_timeout = 10s
[shop]
; Workers run as the application user, not as root and not as the web server's user of another site.
user = www-data
group = www-data
; A Unix socket under /run is owned by the pool; the web server's user must be allowed to write to it.
listen = /run/php-fpm-shop/shop.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
pm = dynamic
pm.max_children = 20
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 6
; Recycle a worker after N requests: a cheap defence against slow leaks in extensions.
pm.max_requests = 500
; Kill a worker that has been serving one request this long: the backstop for when max_execution_time does not stop the script.
request_terminate_timeout = 60s
; Log a PHP backtrace of any request slower than this.
request_slowlog_timeout = 5s
slowlog = /var/log/php-fpm-shop/slow.log
; Keep worker stdout/stderr (not otherwise captured) in the FPM log.
catch_workers_output = yesThe scheduled work itself is ordinary Laravel; what the Linux side adds is the contract around it. The example dispatches queued jobs instead of using runInBackground(): with the default KillMode=control-group systemd kills every process left in the one-shot unit's cgroup when schedule:run exits, so a background child would die with the tick (KillMode=process would spare it, but outside supervision and limits). Laravel itself recommends that sub-minute tasks "dispatch queued jobs or background commands" because schedule:run then keeps running until the end of the minute, which is why the unit sets no start timeout. withoutOverlapping() and onOneServer() are application-level locks (cache-based), the timer is the clock, the unit is the sandbox.
<?php
// routes/console.php (Laravel 13): the schedule that laravel-schedule.timer ticks once a minute.
// Heavy work is dispatched as queued jobs (processed by laravel-queue@N.service), so the one-shot
// tick returns quickly and nothing depends on children that outlive `schedule:run`.
use App\Jobs\BuildDailyReport;
use Illuminate\Support\Facades\Schedule;
Schedule::job(new BuildDailyReport)
->dailyAt('02:00') // evaluated in the app timezone: keep it UTC on servers
->onOneServer(); // one host of a fleet dispatches it (needs a shared cache driver)
Schedule::command('queue:prune-batches')
->daily()
->withoutOverlapping(30); // lock expires after 30 minutes if a run diesThe Laravel angle
- One tick per minute.
schedule:run"will evaluate all of your scheduled tasks and determine if they need to run based on the server's current time" (Laravel 13 scheduling docs); the timer's job is only to start it on the minute, which is whyOnCalendar=*-*-* *:*:00withAccuracySec=1s.php artisan schedule:workis the alternative for a local or container process that ticks itself. - Permissions.
storage/andbootstrap/cachemust be writable by the user that runs PHP-FPM, the scheduler and the workers: the three units use the sameUser=www-data(or a dedicatedshopuser for all three); the code is owned by the deploy user and readable by that group. A scheduler that runs as root creates root-owned log files that PHP-FPM then cannot write. - Deploy sequence. Build,
composer install --no-dev -o, switch thecurrentsymlink,php artisan migrate --force,php artisan optimize,systemctl reload php-fpm-shop(gracefulSIGUSR2, so OPcache starts clean),php artisan queue:restart(workers finish their job and are restarted byRestart=always).queue:restartis Laravel's own signal to workers (stored in the cache); it replacessystemctl restartwhen you want graceful turnover. - FPM sizing.
pm.max_childrentimes the average worker RSS must fit in the memory left after the database and the OS; measure withps.pm.max_requestsrecycles workers;request_terminate_timeoutis the backstop formax_execution_time;slowlogfinds the slow request. See Memory. - Sockets.
listen = /run/php-fpm-shop/shop.sockwithlisten.owner/group/modeand the same group on the web server user; Nginxfastcgi_pass unix:/run/php-fpm-shop/shop.sock;(see Web Servers & Reverse Proxies). Do not expose TCP port 9000 beyond localhost: FPM trusts whoever can connect. - Logs. The
dailychannel writesstorage/logs/laravel-YYYY-MM-DD.logandLOG_DAILY_DAYSsets retention;stderrorsyslogchannels send everything to the journal and need no rotation. Pick one per environment. - Time.
config/app.phptimezonestaysUTC; scheduled times andCarbonoutput follow it. - Containers. The same ideas apply in Docker (one process per container, the scheduler as a second container or
schedule:work); see Images & Dockerfiles and Running Containers.
Solving the classic problems
The service restarts forever or fails with 203/EXEC
Read systemctl status orders-api (the status=203/EXEC or 217/USER part) and journalctl -u orders-api -n 50. 203: the path in ExecStart= is wrong, the file is not executable, the filesystem is mounted noexec, or the binary is for another architecture (file /opt/orders-api/current/orders-api). 217: the User= does not exist (getent passwd orders; run systemd-sysusers). A restart loop with Restart=always and no RestartSec retries every 100 ms and floods the journal until the inherited default start limit trips (an unset StartLimitBurst inherits DefaultStartLimitBurst; it does not disable limiting); set both values on purpose, and systemctl reset-failed clears the state afterwards.
"Permission denied" although the file looks readable
namei -l /var/www/shop/storage/logs/laravel.log prints the mode and owner of every component; one directory without x for your class is enough. Then id www-data (is the user in the group you think?), getfacl, and SELinux (ls -Z, ausearch -m avc -ts recent) or AppArmor (journalctl -k | grep DENIED). Group membership of a running process changes only after it restarts: a user added to a group is not in it for processes already running.
Disk full
Run the steps of the inodes block or the repository's disk-triage.sh: blocks, inodes, deleted-but-open files, a hidden mount. Free space safely (journalctl --vacuum-size=500M, apt clean, old releases under /opt/<svc>/releases), restart the process that holds a deleted file, then fix the cause (rotation with reopen, bounded journal, cache expiry).
#!/bin/sh
# disk-triage.sh: "No space left on device" in five steps. Read-only; safe on production.
set -u
echo "### blocks per filesystem"; df -hT -x tmpfs -x devtmpfs
echo; echo "### inodes per filesystem (IUse% 100 means 'full' with free blocks)"; df -hi -x tmpfs -x devtmpfs
echo; echo "### biggest top-level directories on the root filesystem (-x stays on one filesystem)"
du -xh --max-depth=1 / 2>/dev/null | sort -h | tail -n 8
echo; echo "### deleted files still held open by a process (space is freed only when they close)"
lsof -nP +L1 2>/dev/null | head -n 15
echo; echo "### directories with the most files in /var (inode hogs)"
for d in /var/*; do [ -d "$d" ] && printf '%s %s\n' "$(find "$d" -xdev 2>/dev/null | wc -l)" "$d"; done | sort -rn | head -n 5The service is killed at night (137)
journalctl -k --since yesterday | grep -i -E 'out of memory|killed process' and systemctl show -p Result,NRestarts. A cgroup kill names the unit's cgroup path; a global kill names the victim and its oom_score_adj. Compare MemoryMax with real use over a day, set GOMEMLIMIT or pm.max_children from measurements, add a small swap, and alert on MemAvailable and PSI before the kill happens.
"Too many open files"
Compare ls /proc/<pid>/fd | wc -l with /proc/<pid>/limits. If descriptors keep growing under constant load it is a leak: unclosed resp.Body, unclosed files, a forgotten rows.Close(). If load really needs more, raise LimitNOFILE= in the unit (not limits.conf) and restart; for Nginx raise worker_rlimit_nofile.
A deploy must not drop requests
Atomic switch of a current symlink, systemctl reload where the program supports a reload (kill -HUP, PHP-FPM SIGUSR2), otherwise systemctl restart with a drain on SIGTERM shorter than TimeoutStopSec. With socket activation the listening socket survives the restart, so connections queue instead of being refused. Rollback is ln -sfn <previous release> current plus a restart; the deploy script keeps five releases for that. Strategies beyond one host (blue-green, canary) are Deployment Strategies.
Zombies and runaway children
ps -eo pid,ppid,stat,cmd | awk '$3 ~ /Z/' names the zombies and, through PPID, the parent that fails to wait. Killing the zombie does nothing; fixing or restarting the parent does. In containers, run an init (--init, tini) as PID 1; in a unit, systemd is the parent and reaps its direct child, but grandchildren of a leaky main process still need that process to wait.
Lock-out after an SSH config change
Prevention: keep a second session open, run sshd -t, use systemctl reload, not restart. Recovery: the cloud provider's serial console or rescue disk, mount the root volume, restore the file. A Match block or a drop-in that sets PasswordAuthentication no before any key is installed is the usual cause; sshd uses the first value it finds, so file order in sshd_config.d matters.
The scheduled job did not run
systemctl list-timers --all shows NEXT, LEFT, LAST and PASSED; journalctl -u laravel-schedule.service --since today shows the runs; systemd-analyze calendar '*-*-* 02:30:00' prints the next elapse times of an expression and its normalised form. For cron: grep CRON /var/log/syslog (Debian), journalctl -u cron, and remember the minimal PATH and the different environment.
Choosing
Which distribution for servers and for images
| Need | Choose | Why |
|---|---|---|
| Boring server, long life, wide package set | Debian stable | Conservative, strong security team, small, glibc |
| Latest tooling, LTS, cloud images, vendor support | Ubuntu LTS | Same base with newer userland and a commercial support option |
| Enterprise compliance, vendor-certified stacks | RHEL or Rocky/Alma | SELinux enforcing by default, long support windows |
| Developer workstation tracking upstream | Fedora | New kernels and toolchains, six-month cadence |
| Small container images, immutable appliances | Alpine or distroless | Tiny; musl and BusyBox trade-offs; no systemd |
| Static Go binary, no userland needed | scratch or distroless static | No distribution at all; see Images & Dockerfiles |
Which filesystem and layout
| Workload | Choice | Reason |
|---|---|---|
| Root volume of a general server | ext4 (Debian, Ubuntu) or XFS (RHEL) | The distribution default is the best-tested path |
| Database or large-file volume | XFS or ext4 on its own LVM or cloud volume | Predictable behaviour; resize online |
| Millions of small files (caches, mail) | XFS or ext4 with a generous inode count (mkfs.ext4 -i) | Inodes are the limit on ext4 |
| Snapshots, checksums, compression | Btrfs, or ZFS where licensing allows | Copy-on-write features |
| Ephemeral scratch | tmpfs | RAM-fast, gone at reboot |
| Shared between hosts | NFS or object storage, not for databases | Latency, locking and D-state hangs |
Which scheduler for a recurring job
| Situation | Choice |
|---|---|
| Logs, limits, catch-up after downtime, per-run exit status | systemd timer plus a oneshot service |
| One trivial job on a host you already manage with cron | cron |
| A fleet where jobs must run once somewhere | Application-level lock (onOneServer) or Kubernetes CronJob, not one cron per host |
| Sub-minute or event-driven | A long-running service or a queue worker, not cron |
| Laravel tasks | One schedule:run tick per minute (timer), tasks defined in code |
Which place for logs
| Source | Choice |
|---|---|
| Go service you write | stderr, collected by journald (or the container runtime) |
| Software that insists on files (Nginx, PHP-FPM slow log) | Files under /var/log/<app> with logrotate and a reopen signal |
| Laravel | stderr channel in containers, daily with retention on VMs |
| Anything you must keep or search after the host is gone | Ship off-host (journal forwarding, an agent) and keep local retention short |
In architecture: from a single process to a distributed system
Monolith: one VM, one binary, one database
A single VM runs the Go binary or the PHP-FPM pool, Nginx, Postgres and a cron or timer. Everything in this chapter applies directly: one orders user, one unit, /opt releases with a symlink, journald, a timer for backups, chrony, SSH keys. The failure modes are local and diagnosable with the first-minute commands. The limits are the machine's: memory shared between app and database, a single disk, a reboot is an outage.
Modular monolith: several units on one host
The same codebase runs as several units: orders-api.service, laravel-queue@N.service, a scheduler timer, a migration oneshot. Each has its own MemoryMax, Nice, user and restart policy, so a runaway report cannot starve the web path. Targets (shop.target with Wants= on all of them) give one switch: systemctl start shop.target. Slices (CPUWeight= on system.slice children) express priorities.
Microservices: many hosts, same unit template
Each service gets its own user, directories and unit generated from one template; configuration management (Ansible, cloud-init, Terraform user-data) renders them. Hosts differ by distribution minor version and kernel, so the artefact (a static Go binary, a container image) carries as much as possible, and the host provides only the supervisor, the clock, the network and the limits. Containers move the unit boundary: the supervisor becomes the container runtime or Kubernetes, and the kernel objects (cgroups, namespaces, signals, PID 1) are the same ones described here; read Containers Under the Hood and Kubernetes Workloads next. Pipelines that produce and roll out the artefact (GitHub Actions or GitLab CI building and copying a static Go binary, then an Ansible run or a systemd restart over SSH) are CI/CD Pipelines; in Kubernetes, Helm charts and Argo CD replace the unit files and the SSH step, and the Linux node underneath is the same.
Distributed data: caches, replicas, clocks and logs across hosts
Distribution turns single-host assumptions into questions. Clocks differ between hosts, so chrony, monotonic timers and UTC logs matter more, and "scheduled once" needs a lock (onOneServer, a database advisory lock) rather than one cron per host. Page cache is per host: a cache-warm replica and a cold replica behave differently after a restart, and memory limits on a database host should leave room for its cache. File descriptors, ephemeral ports and somaxconn become fleet-wide capacity numbers. Logs leave the host as they are written, because the host may be replaced; the journal is the local buffer, not the archive. Node-level metrics (node_exporter: load, MemAvailable, PSI, filesystem and inode usage) feed the alerts, as described in Observability.
Scaling path: 1x, 10x, 100x
| Scale | What changes in the Linux layer |
|---|---|
| 1x: one VM | Hand-built, documented by this chapter; unit files and scripts in a repository; backups by timer; alerts on disk, inodes, memory, load |
| 10x: a few VMs behind a balancer | Units rendered by Ansible or cloud-init; same user and directory layout everywhere; graceful reload/restart in the deploy; central logs; time and SSH policy as code |
| 100x: a fleet | Immutable images (rebuild, not patch), unattended security updates replaced by image rotation; autoscaling groups; bastions or SSM instead of direct SSH; eBPF or agent-based observability; kernel and distribution versions tracked as inventory |
| Beyond | Kubernetes or another scheduler: nodes are cattle, the Linux node image is minimal, and the unit file becomes a Pod spec rolled out by Helm or Argo CD; systemd remains on the node (kubelet, containerd) |
Lab
All commands in this lab that need a Linux kernel (systemd, /proc, ss, free, dmesg, chronyc, apt) are labelled expected, not run: the build host is macOS, so the output shown for them is the shape the tools print, not a capture. Every step below starts in the snippet directory: from the repository root run cd docs/snippets/platform/linux-for-developers once, and keep that as the working directory (steps that need the Go module use a subshell). Steps 1 to 3 were run on the macOS build host and their output is the real output, saved in pipeline/sources/linux-for-developers/lab-host-output.txt (Darwin 27.0.0 arm64, Go 1.27.4). macOS has no /proc and no systemd, so the same Go programs run there with a plain ADDR.
1. Test the Go helpers and build the service (ran on the host)
cd go # the Go module root
gofmt -l . # prints nothing
go vet ./...
go test -race -count=1 ./...
go build -o /tmp/orders-api ./service
cd .. # back to the snippet directoryExpected and observed: four packages report ok (exitcode, perms, procfs, service). The perms test creates a real file under umask 027 and compares the kernel's result with the model; the exitcode test starts sh -c 'exit 0', sees the child in state Z through ps, calls Wait and sees the entry disappear.
2. Signals, reload and exit status (ran on the host)
echo v1 > /tmp/greeting
ADDR=127.0.0.1:18081 CONFIG_FILE=/tmp/greeting /tmp/orders-api &
curl -s 127.0.0.1:18081/hello # v1
echo v2 > /tmp/greeting; kill -HUP %1 # re-read without restart
curl -s 127.0.0.1:18081/hello # v2
kill -TERM %1; wait %1; echo "exit status $?" # 0: it drained and returned
sh -c 'kill -KILL $$'; echo "status $?" # 137 = 128 + 9
sh -c 'exit 3'; echo "status $?" # 3Observed on the host: v1, then after SIGHUP v2 with the log line msg="reloaded config" and the same PID, exit status 0 after SIGTERM, status 137 for the self-killed shell, status 3.
3. Modes, umask and links (ran on the host)
(umask 022; touch f022; mkdir d022; umask 077; touch f077); ls -ld f022 d022 f077
ln f022 hard; ln -s f022 sym; ls -li f022 hard sym; rm f022; cat hard; cat symObserved: -rw-r--r-- for f022, drwxr-xr-x for d022, -rw------- for f077; f022 and hard share one inode number (12214868 in the saved run) with link count 2; after rm f022 the content is still readable through hard and sym reports No such file or directory (it dangles). On macOS /usr/bin/sudo shows -r-s--x--x (the setuid bit as s).
4. Create the user and the layout (expected, not run; Debian or Ubuntu, as root)
sudo sh scripts/provision-service-user.sh orders-api orders
# expected last line: uid=991(orders) gid=991(orders) groups=991(orders) (the number differs per host)
ls -ld /opt/orders-api /etc/orders-api /var/lib/orders-api
# expected: drwxr-xr-x root root /opt/orders-api ; drwxr-x--- root orders /etc/orders-api ; drwxr-x--- orders orders /var/lib/orders-api5. Install and run the service (expected, not run)
(cd go && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o ../orders-api-linux-amd64 ./service)
sha256sum orders-api-linux-amd64 # copy the hash
sudo cp systemd/orders-api.service /etc/systemd/system/
sudo install -m 0640 -o root -g orders systemd/orders-api.env /etc/orders-api/orders-api.env
sudo bash scripts/deploy-go-binary.sh orders-api ./orders-api-linux-amd64 <sha256>
systemctl status orders-api
# expected: Active: active (running); Main PID: <n> (orders-api); Status: "serving on 127.0.0.1:8080"
curl -s 127.0.0.1:8080/orders/42 # {"id":"42","uid":<orders uid>,"pid":<n>}
systemd-analyze security orders-api # a table of settings and an overall exposure score; the hardened unit scores well below the default6. Reload, stop and the exit status (expected, not run)
sudo systemctl reload orders-api # SIGHUP: journal shows "reloaded config", PID unchanged
sudo systemctl stop orders-api # SIGTERM: journal shows the drain, then "Deactivated successfully"
systemctl show orders-api -p Result,ExecMainStatus # Result=success ExecMainStatus=0
sudo kill -9 $(systemctl show -p MainPID --value orders-api) # (start it again first)
# expected: the unit restarts after RestartSec; NRestarts increments; Result=signal7. Timers, logs, limits and memory (expected, not run)
sudo install -m 0644 systemd/laravel-schedule.* /etc/systemd/system/ && sudo systemctl daemon-reload
sudo systemctl enable --now laravel-schedule.timer
systemctl list-timers laravel-schedule.timer # NEXT within a minute, LAST empty at first
systemd-analyze calendar '*-*-* *:*:00' # shows the normalised form and the next elapse
journalctl -u laravel-schedule.service --since "5 min ago"
cat /proc/$(systemctl show -p MainPID --value orders-api)/limits | grep 'open files' # 65536 65536
free -m ; cat /proc/loadavg ; sudo dmesg -T | tail -5
sh scripts/triage-60s.sh /tmp/triage.txt # the ten first-minute commands in one file8. Break it on purpose (expected, not run)
sudo chmod 000 /opt/orders-api/current/orders-api && sudo systemctl restart orders-api
systemctl status orders-api # expected: status=203/EXEC (Permission denied)
sudo chmod 755 /opt/orders-api/current/orders-api
sudo userdel orders && sudo systemctl restart orders-api # expected: status=217/USER (then recreate with provision-service-user.sh)Common misconceptions
| Belief | Reality |
|---|---|
| Linux is an operating system | It is the kernel; distributions add the userland, and containers share only the kernel |
kill kills a process | It sends SIGTERM by default, which the program may handle; only SIGKILL and SIGSTOP are uncatchable |
A zombie is a stuck process I can kill -9 | It is already dead; only its parent's wait (or the parent's exit) removes it |
| Free memory should be large | Unused RAM is wasted; watch available and swap activity, not free |
| Load average is CPU usage | It counts runnable plus uninterruptible tasks over damped 1/5/15-minute windows; compare it with the CPU count |
chmod 777 fixes permissions | It removes them; find the directory without x with namei -l and fix owner or group |
| If the group may write, the owner may too | One class applies: owner, else group, else other; the owner class can deny what the others allow |
sudo makes my shell root | It runs one command as another user and logs it |
| Binding port 80 needs root | It needs CAP_NET_BIND_SERVICE, or socket activation, or a proxy on port 80 |
rm frees disk space | It removes a name; space returns when the last link and the last open descriptor go |
df and du must agree | They measure different things; the difference is deleted-but-open files, hidden mounts, sparse files and snapshots |
Editing limits.conf raises a service's limits | That file is for PAM login sessions; services use LimitNOFILE= |
Restart=always makes a service reliable | It hides crashes and loops; use on-failure, RestartSec and a start limit, and alert on NRestarts |
network.target means the network is up | It means the stack is up; use network-online.target when you need an address |
| Cron is enough everywhere | It is fine for trivial jobs; timers add logs, limits, overlap control and catch-up |
| Set servers to the local timezone | Use UTC and convert at the edge; local time duplicates and skips an hour |
Cheat sheet
| Topic | Remember |
|---|---|
| Kernel vs userland | One kernel, many userlands; containers share the host kernel; /etc/os-release names the distribution |
| Packages | apt (Debian, Ubuntu), dnf (RHEL, Fedora), apk (Alpine); update refreshes the index, upgrade installs; owner of a file: dpkg -S, rpm -qf |
| Processes | PID, PPID, fork then exec; ps -eo pid,ppid,user,stat,cmd; /proc/<pid>/ has the truth |
| States | R, S, D (disk wait, immune to signals), T, Z (needs parent's wait) |
| Signals | TERM 15 polite, KILL 9 final, HUP 1 reload, INT 2 Ctrl+C, QUIT 3 dump; exit 137 = KILL, 143 = TERM |
| Users | Numbers matter, names are labels; one system user per service, nologin; id, getent |
| Modes | Octal 4/2/1 per owner, group, other; one class decides; umask clears bits (0666 & ~022 = 0644); X capital for directories |
| Special | setuid 4, setgid 2 (directory inherits group), sticky 1 (/tmp); ACLs setfacl; capabilities replace root |
| Layout | /etc config, /opt your releases, /var/lib state, /var/log, /run volatile, /tmp scratch |
| Disk | df -h, df -i, du -xh, lsof +L1, lsblk -f, findmnt; mount by UUID with nofail |
| systemd | systemctl status/cat/edit/daemon-reload, journalctl -u X -f, systemd-analyze verify/security |
| Unit | User=, Type=notify, Restart=on-failure, TimeoutStopSec, EnvironmentFile, StateDirectory, MemoryMax, NoNewPrivileges, ProtectSystem=strict |
| Timers | OnCalendar, Persistent=true, RandomizedDelaySec; systemctl list-timers |
| Logs | stderr to journald; journalctl -p err -b; logrotate needs a reopen signal; bound the journal |
| Memory | available not free; OOM kills by score plus oom_score_adj; MemoryMax scopes it; dmesg -T shows the kill |
| Load | Compare with CPU count; vmstat 1, iostat -xz 1, mpstat -P ALL, sar; st = hypervisor steal |
| Network | ip -br addr, ss -ltnp, dig +short, getent hosts |
| SSH | Ed25519 keys, IdentitiesOnly, ProxyJump, PermitRootLogin no, PasswordAuthentication no, sshd -t before reload |
| Limits | ulimit -n is shell-only; services use LimitNOFILE=; check /proc/<pid>/limits |
| Time | UTC, chrony, timedatectl, chronyc tracking |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — systemctl stop orders-api takes 15 seconds every time and the journal shows exit status 137. What happened and what do you change? Must-know
Answer
Answer: systemd sent SIGTERM, the process did not exit within TimeoutStopSec (15 s here), so systemd sent SIGKILL to what remained in the cgroup; 137 is 128 + 9. The program probably does not handle SIGTERM, or something between systemd and the program (a shell started through sh -c) swallows it. Handle SIGTERM in the application (signal.NotifyContext in Go), exec the real program in wrapper scripts, drain for less than TimeoutStopSec, and raise the timeout only if the drain truly needs longer.
2 — A file is rw-rw-rw- but you get "Permission denied" opening it. List three causes. Must-know
Answer
Answer: (1) A directory on the path lacks x for your class: namei -l shows which one. (2) A mandatory access control layer (SELinux context, AppArmor profile) denies it despite the modes: ls -Z, ausearch -m avc, journalctl -k | grep DENIED. (3) A systemd sandbox (ProtectSystem=strict, PrivateTmp, InaccessiblePaths) hides or protects the path, or the filesystem is read-only (that blocks writes only). A noexec mount is not a cause here: it forbids executing files from that mount, not opening a readable one. Also possible: the process's groups changed after it started, or an ACL mask caps the entry.
3 — df -h says /var is 100% full but du finds only 2 GB on a 50 GB volume. Why, and how do you recover? Must-know
Answer
Answer: A process holds open a file that was deleted (often a log removed without the service reopening it); the blocks are freed only when the last descriptor closes. lsof +L1 lists unlinked open files; restart or signal the holder, or truncate through /proc/<pid>/fd/<n>. Other explanations: a mount hiding files under it, snapshots, or sparse files. Also check df -i in case inodes, not blocks, are exhausted.
4 — What is the difference between SIGTERM and SIGKILL, and why can a process in D state ignore both? Must-know
Answer
Answer: SIGTERM can be caught, handled or ignored, so a program can finish requests and clean up; SIGKILL cannot be caught, blocked or ignored (signal(7)) and gives no cleanup. A process in uninterruptible sleep (D, typically waiting on disk or NFS) does not act on signals until the kernel call returns, so even SIGKILL is pending until then; the fix is on the storage side.
5 — Why does a service started by systemd ignore the nofile limit you put in /etc/security/limits.conf, and where do you set it? Must-know
Answer
Answer: limits.conf is applied by pam_limits when a PAM session opens (ssh, su, console); systemd starts services without a PAM session for them, so they get LimitNOFILE= from the unit or DefaultLimitNOFILE= from the manager. Set LimitNOFILE=65536 in the unit or a drop-in, restart, and confirm with cat /proc/<pid>/limits.
6 — A Go service binds :443 as user orders. What are three ways to make that work without running as root? Important
Answer
Answer: Grant only CAP_NET_BIND_SERVICE with AmbientCapabilities=CAP_NET_BIND_SERVICE (and CapabilityBoundingSet= limited to it) in the unit; use systemd socket activation so root-owned PID 1 binds the port and passes descriptor 3; or listen on an unprivileged port and let a reverse proxy (Nginx, Caddy) or a load balancer own 80 and 443. setcap on the file also works but is lost when the binary is replaced.
7 — What does Type=notify change compared with Type=simple, and what happens if the program never sends READY=1? Important
Answer
Answer: With simple, systemd considers the unit started as soon as the process is forked; with notify it stays activating until the program sends READY=1 on $NOTIFY_SOCKET, so dependents start only when the service can really serve, and startup failures show up at systemctl start. If the message never arrives the start times out (TimeoutStartSec) and the unit fails.
8 — Why is a systemd timer with Persistent=true better than a cron line for a nightly backup, and when is cron still fine? Important
Answer
Answer: Persistent=true runs the job once at the next start when a run was missed while the machine was off; the job's output and exit status are in the journal; the service can carry Nice=, memory limits and a sandbox; a running one-shot is not started twice; RandomizedDelaySec spreads load. Cron is fine for trivial, host-local jobs on systems without systemd or where you already operate cron and need none of this.
9 — How do available memory, oom_score_adj and MemoryMax relate, and what does exit 137 after a memory spike tell you? Important
Answer
Answer: available (MemAvailable) estimates memory obtainable without swapping and is the number to monitor. oom_score_adj (-1000 to +1000) shifts the badness score the OOM killer uses to pick a victim; MemoryMax makes the kernel kill inside the service's own cgroup instead of choosing across the host. 137 means the process died from SIGKILL, here most likely the OOM killer; confirm in dmesg -T or the journal, then size limits from measurements.
10 — Load average is 12 on a 4-CPU box but top shows the CPUs mostly idle. What do you look at? Important
Answer
Answer: Linux load includes tasks in uninterruptible sleep, so a storage or NFS stall inflates it. Look at wa in top, vmstat 1 (b blocked, bi/bo), iostat -xz 1 (await, %util), ps for D states, dmesg for I/O errors, and PSI /proc/pressure/io. If st is high, the hypervisor is taking the CPU instead.
11 — Why should SSH password logins be off, and how do you change sshd_config without locking yourself out? Important
Answer
Answer: Passwords can be guessed and are the target of constant scanning; keys are not guessable and can be restricted per key. Install and test your key first, keep one session open, put the change in a drop-in under sshd_config.d, run sshd -t, systemctl reload ssh, and open a second session before closing the first. Remember that sshd takes the first value it finds for an option.
12 — A hard link and a symbolic link to the same file: what happens to each when the original name is removed? Good to know
Answer
Answer: The hard link is another name for the same inode, so the content stays and the link count drops from 2 to 1. The symbolic link stores a path and now points to nothing (it dangles). Hard links cannot cross filesystems or point to directories; symbolic links can.
13 — Why run servers in UTC, and what does chrony's makestep 1.0 3 do? Good to know
Answer
Answer: UTC has no daylight-saving jumps, so logs are unambiguous and schedulers never skip or repeat an hour; convert to local time only at the edge. makestep 1.0 3 lets chronyd step the clock (instead of slewing slowly) when the offset exceeds 1 second, but only during the first three clock updates after chronyd starts. That limits stepping on a long-running daemon, but a restarted chronyd counts again from zero and may step; the chrony documentation recommends stepping only at boot, before programs that rely on time advancing monotonically.
Glossary
| Term | Meaning |
|---|---|
| Kernel | The privileged core that schedules processes, manages memory, drivers, filesystems and permissions |
| Userland | Everything outside the kernel: shell, libraries, tools, init system |
| Distribution | A packaged combination of kernel, userland, package manager and release policy |
| glibc / musl | The two common C libraries on Linux; Alpine uses musl |
| Package manager | Tool that installs, upgrades and removes signed packages (apt, dnf, apk) |
| Repository | A signed collection of packages and an index served over HTTP |
| Process | A running program instance with PID, memory, descriptors and credentials |
| PID / PPID | Process ID and its parent's ID; PID 1 is init |
| fork / exec | Duplicate the calling process / replace its program image |
| Zombie | A terminated process whose exit status has not yet been read by its parent |
| Orphan | A live process whose parent died; adopted by PID 1 or a subreaper |
| Signal | An asynchronous notification delivered to a process (SIGTERM, SIGKILL, SIGHUP ...) |
| Exit status | The number a process returns; 128 + n for death by signal n in a shell |
| Niceness | Scheduling weight from -20 to 19; higher means more polite |
/proc | Pseudo-filesystem exposing kernel and process state as files |
| UID / GID | Numeric user and group identities the kernel checks |
| Effective / saved UID | The identity used for checks / the copy kept by setuid programs |
| Mode | Permission bits (rwx for owner, group, other) plus setuid, setgid, sticky |
| umask | Bits removed from the mode of newly created files and directories |
| setuid / setgid | Run an executable with its owner's or group's identity |
| Sticky bit | On a directory: only the owner of an entry may delete or rename it |
| ACL | Access control list: named users and groups on top of the mode bits |
| Capability | One privilege split out of root (for example CAP_NET_BIND_SERVICE) |
| FHS | Filesystem Hierarchy Standard: what lives in /etc, /var, /usr, /opt, /tmp |
| Mount | Attaching a filesystem at a directory |
fstab | File listing filesystems to mount at boot |
| Inode | Record holding a file's metadata and block pointers, not its name |
| Hard link / symlink | A second name for an inode / a file containing a path |
| LVM | Logical Volume Manager: physical volumes, volume groups, logical volumes |
| Swap | Disk space used as overflow for memory pages |
| systemd | PID 1 service manager with units, dependencies, cgroups and a journal |
| Unit | Configuration object systemd manages (service, timer, socket, target, mount ...) |
| Target | A unit grouping others into a boot or runtime state |
| Drop-in | A .d/*.conf file that overrides parts of a unit |
| Socket activation | systemd binds the socket and starts the service on the first connection |
Type=notify | Unit type that waits for the program to send READY=1 |
| cgroup | Kernel group of processes with resource limits and accounting |
| Journal / journald | systemd's structured log store and collector |
| rsyslog | Classic syslog daemon writing text logs and forwarding them |
| logrotate | Tool that rotates, compresses and prunes log files |
| Page cache | RAM used to cache file contents; reclaimable |
| OOM killer | Kernel mechanism that kills a process when memory cannot be reclaimed |
oom_score_adj | Per-process offset (-1000 to +1000) added to the OOM badness score |
| Load average | Exponentially damped count of runnable plus uninterruptible tasks over 1, 5, 15 minutes |
| CPU steal | Time a virtual CPU waited because the hypervisor ran another guest |
| PSI | Pressure Stall Information: time tasks spent stalled on CPU, memory or I/O |
| File descriptor | Small integer naming an open file, socket or pipe in a process |
rlimit / ulimit | Per-process resource limits (soft and hard) |
| chrony | NTP implementation that keeps the system clock accurate |
| NTP | Network Time Protocol |
| Locale | Language and formatting settings (LANG, LC_*) |
| SSH key pair | Public and private key used instead of a password |
sshd | The SSH server daemon |
| Bastion / ProxyJump | A host used to reach private hosts; the SSH option that hops through it |
| Service user | A non-login system account that owns one service's process and files |
EnvironmentFile | Unit setting that loads KEY=value lines into the service environment |
| PHP-FPM | FastCGI process manager that runs PHP workers behind a web server |
References
- Linux manual pages (man7.org): proc(5), proc_pid_oom_score_adj(5), signal(7), capabilities(7), credentials(7), chmod(1), umask(2), fork(2), wait(2), execve(2), getrlimit(2), inode(7), hier(7), fstab(5), free(1), nice(1), limits.conf(5), logrotate(8), ss(8), ip(8), iostat(1), vmstat(8), setfacl(1)
- systemd documentation (freedesktop.org): systemd.unit, systemd.service, systemd.timer, systemd.exec, systemd.kill, systemd.resource-control, systemd.socket, systemctl, journalctl, journald.conf, sd_notify, sd_listen_fds, sd-daemon, tmpfiles.d, sysusers.d, systemd-analyze, systemd.time, timedatectl
- Filesystem Hierarchy Standard 3.0: https://refspecs.linuxfoundation.org/FHS_3.0/fhs-3.0.html
- Linux kernel documentation: cgroup v2, sysctl vm, PSI, ext4, XFS, Btrfs, uapi capability.h
- Brendan Gregg: Linux Load Averages: Solving the Mystery, Linux Performance Analysis in 60s, Linux Performance
- Packages: apt-get(8), apt(8), dnf command reference, Alpine Package Keeper, Debian SecureApt, UnattendedUpgrades, dpkg(1), rpm(8)
- Releases: Debian, Ubuntu release cycle, Alpine, Fedora life cycle, LWN: The road forward for systemd, kernel.org about
- Storage: Red Hat: configuring and managing logical volumes
- SSH and sudo: sshd_config(5), ssh_config(5), ssh-keygen(1), sudoers, sudo
- Time: chrony.conf, rsyslog documentation
- Go: os/signal, os/exec, net/http server, Go 1.19 release notes, Go 1.25 release notes, GC guide, log/slog blog
- Laravel 13: Task scheduling, Queues, Deployment, Logging
- PHP-FPM: Installation, Configuration, php-fpm.8 (signals)