Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why one kernel, many systems, and why a process modelWhy it exists
The Unix model, Linux, systemd 2010, cgroup v2 and today's releasesWhere it comes from
Kernel vs userland, distributions, Debian/Ubuntu vs RHEL/Fedora vs AlpineKernel, userland, distributions
Package managers: apt, dnf, apk; repositories, signatures, pinningPackage managers
Processes, PID, parent/child, fork and execProcesses
Process states, zombies, orphansProcess states
Signals, SIGTERM vs SIGKILL, SIGHUP, exit codes (137, 143)Signals and exit codes
Nice and priorities, /proc, ps, top, htopPriorities and inspection
Users and groups, UID GID, root and sudo, service usersUsers and groups
File permissions, rwx, octal modes, umask, ownershipPermissions
setuid setgid sticky bit, ACLs, capabilitiesSpecial bits, ACLs, capabilities
Filesystem hierarchy standard: /etc /var /usr /opt /tmpThe hierarchy
mount, fstab, ext4 vs xfs vs btrfs, LVM, swapMounts, filesystems, LVM, swap
Inodes, hard and symbolic links, disk usage (df du, lsblk)Inodes, links, disk usage
systemd, units, services, targets, systemctlsystemd
Writing a unit, environment files, hardening, limitsWriting a service unit
Timers vs cronTimers
Logs, rsyslog and journald, journalctl, log rotation with logrotateLogs
Memory, free, the OOM killer, oom_score_adjMemory and the OOM killer
Load average, CPU steal, iostat vmstat sar, PSICPU, load, I/O
Network basics (ip, ss, dig) link to the networking chaptersNetwork basics
SSH keys and config (~/.ssh/config), sshd hardening basicsSSH
ulimit and limits.conf, file descriptorsLimits
Time and NTP, chrony, locales and timezonesTime, locales
Build graph of a boot, errors you will see, knobsMechanics
Service user for a Go binary; deploying a Go binary as a systemd serviceGo
PHP-FPM pool as a systemd unit; Laravel scheduler as a systemd timer; queue workersLaravel
Nine classic problems and their fixesSolving the classic problems
Which distribution, filesystem, scheduler, log pathChoosing
One VM to a fleetIn architecture
Commands with expected outputLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The objects you meet, and the command that shows each one.

ObjectWhat it isFirst command to look at it
ProcessA running program with a PID, a parent, a user, open files, an environment and memoryps -eo pid,ppid,user,stat,etime,cmd, ls -l /proc/<pid>/
SignalA small integer message to a process; most can be caught, SIGKILL and SIGSTOP cannotkill -l, kill -TERM <pid>, strace -e signal
User, groupNumbers (UID, GID) that the kernel checks; names are a lookup in /etc/passwdid, getent passwd orders
File modeNine permission bits (owner, group, other) plus setuid, setgid, stickyls -l, stat -c '%a %U:%G %n' file
InodeThe record with owner, mode, size, timestamps and block pointers; names point to itls -i, stat, df -i
MountA filesystem attached at a directory; /etc/fstab lists the permanent onesfindmnt, lsblk -f, df -hT
UnitA thing systemd manages: service, timer, socket, target, mount, pathsystemctl list-units, systemctl cat orders-api
cgroupA tree of process groups with resource limits and accounting; one per servicesystemd-cgls, systemctl status, /sys/fs/cgroup/
Journalsystemd's structured log store, indexed by unit, priority, boot, timejournalctl -u orders-api -f
MemoryAnonymous pages, page cache, swap; the OOM killer is the last resortfree -h, cat /proc/meminfo, dmesg
SocketAn endpoint a process listens on or connects withss -ltnp, ss -s
ClockSystem time kept right by chrony; timezone is presentationtimedatectl, chronyc tracking

The distribution families.

FamilyPackage format and toolTypical useRelease rhythm (from the vendors' pages, 2026-11-29)Service manager, libc
Debian.deb, apt, dpkgStable servers, base of many imagesDebian 13 "trixie" released 9 August 2025systemd, glibc
Ubuntu.deb, apt, snapCloud VMs, developer laptops, LTS serversLTS every two years (24.04 LTS, 26.04 LTS on Canonical's page)systemd, glibc
RHEL, Rocky, Alma, CentOS Stream.rpm, dnf, rpmEnterprise, regulated environmentsMajor releases with multi-year support (Red Hat lifecycle page)systemd, glibc, SELinux enforcing
Fedora.rpm, dnfDeveloper workstation, upstream of RHELNew release about every six months, "approximately 13 months" of updatessystemd, glibc, SELinux enforcing
Alpine.apk, apkSmall container base images, routersA 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.

SymptomFirst commandWhat you are checking
Service will not startsystemctl status orders-api, then journalctl -u orders-api -n 50 --no-pagerExit status, the last log lines, restart counter
"Permission denied"namei -l /path/to/file, idEvery directory in the path needs x for your class
"No space left on device"df -h then df -i then lsof +L1Blocks, inodes, deleted-but-open files
Process gone, exit 137dmesg -T, journalctl -k, systemctl statusOOM killer or a cgroup limit
Everything slowuptime, vmstat 1 5, iostat -xz 1 3, free -mLoad, run queue, swap, disk wait, steal
"Connection refused"ss -ltnp, curl -vIs anything listening, on which address
Wrong time in logstimedatectl, chronyc trackingSynchronised? Which timezone?
Cron job did not runsystemctl 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-offWhat you getWhat it costs
Everything is a file or a processOne vocabulary (open, read, kill) for devices, sockets, kernel stateNames hide very different things; /proc/meminfo is not a file on disk
Discretionary permissions (owner decides)Simple, fast, predictableEasy to over-grant; a compromised owner account has everything that owner has
One kernel, many distributionsChoice of package manager, release rhythm, libcThe 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, loggingUniform units, dependencies, cgroup limits, sandboxingA large surface to learn; some distributions (Alpine) choose a different init
Overcommit and the page cacheFast, efficient use of RAM"Free" memory looks small, and when memory really runs out the kernel kills a process
Text configuration under /etcDiff-able, version-controlled, automatableNo 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 ​

  1. "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.
  2. "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 is available.
  3. "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 ​

WhenWhat happenedSource
Unix originsThe model this chapter describes: processes created by fork and execve, users and group IDs, permission bitsfork(2), execve(2), credentials(7) document today's form
1988-1990POSIX.1 standardises the Unix interface that Linux later implements ("P1990" in the signal table of signal(7) means POSIX.1-1990)signal(7)
LinuxThe kernel is by Linus Torvalds "with assistance from a loosely-knit team of hackers"; distributions combine it with a userlandkernel.org about page
1993A three-line change makes Linux load averages include uninterruptible tasks, so the number reflects disk demand tooBrendan Gregg, "Linux Load Averages: Solving the Mystery"
Linux 2.2 (1999)Superuser privilege split into capabilitiescapabilities(7)
April 2010Lennart Poettering announces systemd, built on socket activation as the "core change"LWN, "The road forward for systemd", 26 May 2010
2016 onwardscgroup v2, a single unified hierarchy ("cgroup v2 has only single hierarchy"), replaces v1; systemd and container runtimes move to itkernel cgroup-v2 documentation
9 August 2025Debian 13 "trixie" stable; point release 13.8 on 21 November 2026debian.org releases page
June 2026Alpine 3.24 released, supported until 2028-06-01alpinelinux.org releases page
2026Ubuntu 26.04 LTS is the current LTS on Canonical's release-cycle pageubuntu.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.

text
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 pty

Real scenarios:

  • A binary built on Ubuntu 26.04 fails on an older RHEL with a "version GLIBC_x.y not 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/sh is BusyBox ash and there is no bash; the same script passes on Debian where /bin/sh is dash. Write #!/bin/sh scripts to POSIX or install bash deliberately.
  • 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.
DistributionPackage toolC library and initNotes (sourced where quoted)
Debian stableapt, dpkgglibc, systemdDebian 13 "trixie" released 9 August 2025 (debian.org); common server and container base
Ubuntu LTSapt, snapglibc, systemdDebian-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 Streamdnf, rpmglibc, systemdOn RHEL "Enforcing mode is the default, and recommended, mode of operation" for SELinux (Red Hat docs)
Fedoradnfglibc, systemdNew release about every six months, updates for "approximately 13 months" (Fedora docs); upstream of RHEL
Alpineapkmusl, 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".

TaskDebian, UbuntuRHEL, FedoraAlpine
Refresh the indexapt updatednf makecache (done automatically)apk update
Installapt install nginxdnf install nginxapk add nginx
Upgrade everythingapt upgradednf upgradeapk upgrade
Remove, and unused dependenciesapt remove x, apt autoremovednf remove xapk del x
Which package owns a filedpkg -S /usr/bin/lsrpm -qf /usr/bin/lsapk info -W /usr/bin/ls
Files in a packagedpkg -L nginxrpm -ql nginxapk info -L nginx
Searchapt search, apt-cache policy xdnf search, dnf info xapk search x
Repositories/etc/apt/sources.list.d/*.sources/etc/yum.repos.d/*.repo/etc/apk/repositories
Hold a versionapt-mark hold xdnf versionlock add x (plugin)apk add 'x=1.2.3-r0' pin in world
Unattended security updatesunattended-upgradesdnf-automaticcron plus apk upgrade (no standard tool)
text
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 drop

Real scenarios:

  • A server is missing a patch released a month ago because apt update was never scheduled; unattended-upgrades handles 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 curl and 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.

text
$ 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-api works 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/exec must Wait() for each child or leave zombies (see States); the repository's exitcode package shows how.
ToolWhat it shows about processes
ps -eo pid,ppid,user,stat,etime,rss,cmdSnapshot with parent, owner, state, elapsed time, resident memory
pstree -apThe parent/child tree with PIDs and arguments
pgrep -af orders, pkillFind or signal by name or pattern (use -x for an exact name)
ls -l /proc/<pid>/exe /proc/<pid>/cwd /proc/<pid>/fdBinary, working directory, open files and sockets
systemd-cglsProcesses grouped by unit and slice
lsof -p <pid>, ss -ltnpOpen 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.

text
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 exits

Real scenarios:

  • A long-running Go service starts exec.Command("convert", ...) with Start() and never calls Wait(): thousands of <defunct> entries accumulate and eventually fork: 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 D after an NFS server vanished ignores SIGKILL until the I/O returns or times out; load average rises because Linux counts D tasks in it.
  • top shows 2 zombie: harmless in number; a growing count means one parent is leaking.
Stateps STATCauseWhat to do
Running or runnableROn CPU or in the run queueLook at CPU, pidstat, perf
SleepingSWaiting for I/O, a timer, a lock, a socketNormal; check what with cat /proc/<pid>/wchan, strace -p
UninterruptibleDWaiting on disk or a kernel lockCheck storage health; iostat -xz; do not expect kill to work
StoppedTSIGSTOP, Ctrl+Z, a debuggerkill -CONT <pid> or fg
ZombieZExited, parent has not waitedFix the parent (call Wait), or restart it
Idle kernel threadIKernel worker with nothing to doIgnore

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".

A process from fork to reapingparent (PID 1200)systemd or a shellchild after forkPID 4821, copy of parentsame PID after exec/opt/orders-api/currentfork()execve()PID, PPID, UID, GID,open fds survive execStates (ps STAT column)R runningon CPU or queuedS sleepingwaits; a signal wakes itD disk waitignores signals, counts in loadT stoppedSIGSTOP / Ctrl+ZEndingexit(n) or killedn = 0..255; signal death = 128+sigZ zombieonly the status is keptgone from the tablePID can be reused laterwait()SIGTERM 15: polite, catchable, the default of kill and of systemd stopSIGKILL 9: cannot be caught or ignored; no cleanup runs; a D-state process dies when it wakesSIGHUP 1: terminal closed; by convention daemons re-read their configurationAn orphaned child is re-parented to PID 1 (or a subreaper), which reaps it
text
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 journal

Real scenarios:

  • A deploy script runs kill -9 on 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 stop or Kubernetes sends SIGTERM to PID 1; if the app is started through sh -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 143 in CI means the job was cancelled with SIGTERM, not that the program failed.
SignalNumberDefaultTypical use in this stack
SIGTERM15TerminateGraceful stop: systemd, Docker, Kubernetes; Go signal.NotifyContext; Laravel workers finish the job
SIGKILL9Terminate, uncatchableLast resort after the stop timeout; OOM killer
SIGINT2TerminateCtrl+C in a terminal
SIGHUP1TerminateReload configuration (nginx, many Go services); terminal closed
SIGQUIT3Terminate and core dumpGo prints all goroutine stacks and exits; PHP-FPM graceful stop
SIGUSR110 (x86)Terminatenginx and PHP-FPM reopen logs (after logrotate)
SIGUSR212 (x86)TerminatePHP-FPM graceful reload; nginx binary upgrade
SIGCHLD17 (x86)IgnoreA child exited; the parent should wait
SIGSTOP / SIGCONT19 / 18 (x86)Stop / resumeDebugging, 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.

text
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
ToolUseKey flags and keys
psOne snapshotps aux, ps -eo pid,ppid,%cpu,%mem,stat,cmd --sort=-%mem, ps -ef --forest
topLive view1 per-CPU, M sort by memory, P by CPU, c full command, H threads, k kill; -b -n 1 for scripts
htopFriendlier topF5 or t tree, F6 sort, F4 filter, F9 or k signal (htop manual); a separate package
pidstat 1Per-process rates-d I/O, -r memory faults, -w context switches
nice -n 10 cmd, renice -n 5 -p PIDStart or change nicenessRange -20..19
ionice -c3 cmdIdle I/O classOnly effective with some I/O schedulers
systemd Nice=, CPUWeight=, IOWeight=Same through a unitSee 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.

text
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=orders

Real 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 docker group "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-data on Debian, nginx or apache on RHEL, www-data or nobody on Alpine images) differs by distribution; configuration that hard-codes the name breaks on migration.
ConcernDebian, UbuntuRHEL, FedoraAlpine
Admin group for sudosudowheelwheel (with doas or sudo installed)
Create system useradduser --system or useradd --systemuseradd --systemadduser -S, addgroup -S (BusyBox)
Web server userwww-datanginx or apacheset by the package (nginx for the nginx package)
Default shell for system users/usr/sbin/nologin/sbin/nologin/sbin/nologin
Declarative userssystemd-sysusers (/etc/sysusers.d/*.conf)samenot 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).

One class decides: owner, else group, else otheropen("/srv/f", O_RDWR)process: uid 991, groups 991,33uid == file owner?yes: use the owner bitsfile GID in process groups?yes: use the group bitsnono: use the other bitsMode 0 7 5 0 (rwxr-x---)special0 = noneowner 7r4 + w2 + x1group 5r4 + x1other 0nothingspecial: setuid 4, setgid 2, sticky 1directory x = may enter (traverse)umask: bits to remove from what the program asked forrequested 0666 (new file)umask 0027 clears g-w and o-rwxresult 0640mode & ~umaskRoot (UID 0) passes the read/write check without any bit; a capability such as CAP_DAC_OVERRIDE is what grants that.ACLs add named users and groups to this check (getfacl / setfacl); the mask entry caps their rights.If the owner class denies, group and other are never consulted, even if they would allow.
text
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.log

Real scenarios:

  • Laravel returns 500 because storage/ and bootstrap/cache are not writable by the PHP-FPM user: chown -R deploy:www-data then chmod -R g+rwX (capital X adds execute only to directories and already-executable files), and chmod g+s on directories so new files inherit the group.
  • A secret file with mode 0644 in /etc/orders-api/: every local user can read it. 0640 root:orders lets only the service read it.
  • A cron job creates reports under umask 0077; the web server cannot read them. Set UMask=0027 in 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.
ModeSymbolicMeaningTypical use
0644rw-r--r--Owner writes, everyone readsConfig that is not secret, static files
0600rw-------Owner onlySSH private keys, .env for a login user
0640rw-r-----Owner writes, group readsService config readable by the service group
0755rwxr-xr-xOwner full, others read and enterBinaries, public directories
0750rwxr-x---Owner full, group read and enterService directories
0775rwxrwxr-xGroup may writeShared deploy directories (with setgid)
1777rwxrwxrwtAnyone 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, mode 4755). /usr/bin/sudo and passwd rely on it. ls shows s (-rwsr-xr-x); a capital S means 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 /tmp is mode 1777.
  • 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 -l shows 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 with getpcaps <pid> or the CapEff line in /proc/<pid>/status; the procfs package decodes that mask.
text
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_SERVICE

Real scenarios:

  • A shared upload directory drwxrwsr-x deploy www-data (setgid) keeps every new file in group www-data without any chmod afterwards.
  • A scan finds -rwsr-xr-x on a helper binary nobody remembers: a privilege-escalation candidate; find / -xdev -perm -4000 -type f lists all setuid files.
  • A backup user needs read access to /var/lib/orders-api without 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-api binds :443 as 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's AmbientCapabilities is the safer place.
MechanismGranularityWhere it is setRisk
Mode bitsowner, group, otherchmodOver-broad groups; world-writable files
setuid / setgidthe program's identitychmod u+s, g+sPrivilege escalation through bugs in the program
Sticky bitdeletion in a shared directorychmod +tForgetting it on a shared directory
POSIX ACLsnamed users and groupssetfaclInvisible in plain ls -l; backups and cp may drop them
Capabilitiesone root power at a timeunit file, setcap, container runtimeSome (CAP_SYS_ADMIN) are close to full root
SELinux / AppArmorlabels or path profiles on top of all of the abovepolicyRHEL'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.

PathHoldsWho writes itFor your service
/etcHost-specific configuration, textroot, packages, you/etc/orders-api/orders-api.env, /etc/systemd/system/*.service
/usrDistribution-owned programs, libraries, docs (read-mostly)package managerDo not install your own files here; /usr/local is the exception for locally built software
/usr/localSoftware you built or installed outside the package manageryouScripts such as /usr/local/libexec/orders-backup.sh
/optSelf-contained add-on products, one directory per vendor or packageyou, vendor packages/opt/orders-api/releases/<id>/orders-api and a current symlink
/var/libPersistent state of programsthe serviceStateDirectory=orders-api creates /var/lib/orders-api
/var/logLogs written as files (journald's binary journal is in /var/log/journal)services, rsyslog/var/log/php-fpm-shop/, Nginx logs
/var/cacheRegenerable cachethe serviceSafe to delete; the app must rebuild it
/var/spool, /var/mailQueues awaiting processingMTA, cronRarely yours
/runRuntime state (PID files, sockets), a tmpfs cleared at bootservices via RuntimeDirectory=/run/php-fpm-shop/shop.sock
/tmp, /var/tmpScratch; /tmp may be cleared at boot, /var/tmp survives rebootsanyoneUse PrivateTmp=yes so a service gets its own
/srvData served by this systemyou/srv/shop is a common web root
/home, /rootPeople's filesusersServices do not live here
/proc, /sys, /devKernel state, devices (not on disk)the kernelRead-mostly; see Priorities and inspection
text
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 all

Real 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).

FilesystemStrengthWeaknessChoose it for
ext4Mature, default on Debian and Ubuntu, simple repair tools, inode count fixed at creationOffline shrink only; no snapshots or checksumsGeneral servers, boot and root volumes
XFSScales to large files and parallel I/O, default on RHEL, dynamic inode allocation, online growCannot shrinkDatabases, media, big log volumes, RHEL family
BtrfsCopy-on-write, snapshots, checksums, subvolumes, compression (kernel documentation: "a copy on write filesystem")More tuning; RAID 5/6 modes have a history of caveatsWorkstations, snapshot-heavy setups (Fedora desktop default)
tmpfsIn RAM, lost at rebootCounts against memory/run, /dev/shm, scratch
overlayfsLayered view over directoriesNot a disk filesystemContainer images, see Containers Under the Hood
NFS, CIFSNetwork filesystemsLatency, D-state hangs when the server vanishes, different lockingShared media; avoid for databases
text
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 online

Real 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.

ToolCommandPurpose
Mount infofindmnt, mount, /proc/mountsWhat is mounted, with options
Block deviceslsblk -f, blkidDisks, partitions, UUIDs, filesystem types
Usagedf -hT, df -hiBlocks and inodes per filesystem
LVMpvs, vgs, lvs, lvextend -rInspect and grow
Swapswapon --show, free -h, vm.swappinessSize and eagerness
Repairfsck, 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.

Names, inodes and data blocksdirectory /srv/appreport.csv -> inode 2051report.hard -> inode 2051report.sym -> inode 2077logs -> inode 3010 (dir)a directory is a list of name -> inodeinode 2051owner 991:991, mode 0640size, atime/mtime/ctimelink count = 2, block pointersinode 2077 (symlink)content: "report.csv" (a path)data blocksthe file's bytesfreed when link countand open fds are 0resolved by path, may dangleWhere the "disk full" confusion comes fromdf -h: blocks 100%or a deleted file still opendf -i: inodes 100%millions of tiny files, blocks freelsof +L1lists unlinked but open filesHard links cannot cross filesystems or point at directories; symlinks can do both. ext4 fixes the inode count at mkfs time; XFS and Btrfs allocate them dynamically.rm removes a name (unlink); the inode lives on while another name or an open file descriptor refers to it.
text
"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 why

Real scenarios:

  • Laravel's storage/framework/cache or session files create millions of small files; df -h shows free blocks, df -i shows 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 ln instead of cp is a second name for the same inode: editing one edits both and a disk failure loses both.
  • ls -l on a symlink shows -> target; deploy/current -> releases/20261129T0912Z is how an atomic switch works.
ToolCommandReads
Capacity, blocksdf -hTSuperblock of each mounted filesystem
Capacity, inodesdf -hiSame, inode counts
Directory sizesdu -xh --max-depth=1 /var | sort -h, ncduWalks the tree; -x stays on one filesystem
Open deleted fileslsof +L1, ls -l /proc/<pid>/fdLink count below 1
Block deviceslsblk -fDisks, partitions, types, UUIDs, mount points
One filestat file, ls -liInode number, links, times, mode
Linksln target name, ln -s target name, readlink -fCreate, 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.

Units: a target pulls services, timers start services, sockets start servicesdefault.target (graphical or multi-user)multi-user.targetWants=orders-api.serviceType=notify, User=orderslaravel-schedule.timerOnCalendar=*-*-* *:*:00php-fpm-shop.servicemaster + pool workerslaravel-schedule.serviceType=oneshot: runs, exits, inactivetimer activates its serviceorders-api.socketListenStream=127.0.0.1:8080first connection, fd 3cgroup (system.slice)MemoryMax, TasksMax, CPUAfter= / Before= decide order only; Wants= / Requires= decide what is started. A unit needs both to start after its dependency.Every service runs in its own cgroup, so stop kills the whole group, and journalctl -u filters its logs.
text
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 clear

Real scenarios:

  • systemctl status orders-api prints Active: activating (start) for 90 seconds then failed: the unit is Type=notify and the program never sent READY=1; fix the program, or use Type=simple.
  • An edit to a unit file has no effect: systemctl daemon-reload was not run (systemctl status warns "changed on disk").
  • A service starts before the network is configured and fails to bind its address: After=network-online.target plus Wants=network-online.target; network.target alone only means "the network stack is up".
  • A Docker or Podman container is itself supervised by a unit (docker.service, or a Quadlet .container file).
CommandWhat it does
systemctl status orders-apiState, main PID, cgroup tree, last 10 log lines, restart counter
systemctl enable --now orders-apiStart at boot and start now
systemctl restart vs reloadStop and start vs signal the running process (ExecReload=)
systemctl cat orders-apiThe unit with all drop-ins merged and their file paths
systemctl edit orders-apiCreate or edit a drop-in (override.conf) and reload
systemctl list-dependencies orders-apiThe dependency tree
systemctl --failed, reset-failedFailed units; clear the failure state
systemd-analyze verify unit, security unit, blameLint a unit, score its sandbox, list boot time by unit
systemctl get-default, isolate multi-user.targetThe 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.

ini
# /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.target
text
reading 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 cgroup

Real scenarios:

  • A deployment writes /etc/orders-api/orders-api.env with DATABASE_URL; the unit reads it as the service user because the file is root:orders 0640. A secret in Environment= would sit in a world-readable unit file and in systemctl show output.
  • A restart storm: Restart=always with no RestartSec and no start limit restarts a crashing Go binary every 100 ms (the documented default RestartSec) until the manager's default start limit (DefaultStartLimitIntervalSec and DefaultStartLimitBurst, inherited when the unit sets nothing) trips; set RestartSec and StartLimitBurst/StartLimitIntervalSec (in [Unit]) deliberately, since an interval of 0 disables limiting altogether.
  • A service needs to write one directory: with ProtectSystem=strict add ReadWritePaths=/srv/uploads or StateDirectory=; "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=stop ends the unit cleanly, Restart=on-failure brings a fresh one.
SettingEffectUse when
Type=simple, exec, forking, oneshot, notifyWhen systemd considers the unit startednotify for programs that can send READY=1; oneshot for jobs
User=, Group=, DynamicUser=yesRun as a non-root user; DynamicUser allocates a transient UIDEvery service; dynamic users when you want no account to manage
Restart=, RestartSec=, StartLimitBurst=Recovery policyon-failure for daemons, none for one-shots
ExecReload=What systemctl reload runsThe program can re-read config on a signal
TimeoutStopSec=, KillSignal=, KillMode=How the stop is escalatedKillSignal=SIGQUIT for PHP-FPM; default control-group otherwise
LimitNOFILE=, LimitNPROC=Per-process rlimitsHigh-connection servers
MemoryHigh=, MemoryMax=, CPUQuota=, TasksMax=cgroup limitsNoisy neighbours; protect the box
NoNewPrivileges=, ProtectSystem=, ProtectHome=, PrivateTmp=, RestrictAddressFamilies=, SystemCallFilter=, CapabilityBoundingSet=SandboxAlways start from systemd-analyze security
Environment=, EnvironmentFile=VariablesNon-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.

ini
# 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.target

Timers 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.

ini
# /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
ini
# /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
Aspectcron (crontab -e, /etc/cron.d)systemd timer
DefinitionOne line, five time fieldsTwo unit files
LogsMail or a redirect you writejournalctl -u orders-backup, with exit status
Missed run (machine off)Skipped (anacron is a separate tool)Persistent=true catches up once
OverlapStarts a second copyA running oneshot is not started again
EnvironmentMinimal, differs from a login shellDefined by the unit; same as any service
Limits, sandbox, prioritynice by handNice=, MemoryMax=, ProtectSystem= ...
JitterNeeds sleep $RANDOMRandomizedDelaySec=
Observabilitygrep CRON /var/log/syslogsystemctl list-timers shows last and next run
PortabilityEvery Unixsystemd 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.

text
# /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
}
ini
# /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=10000
text
where 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=.

SourceWhereRotationReopen
journald/var/log/journal or /run/log/journalBuilt-in (SystemMaxUse=, MaxRetentionSec=)n/a
rsyslog files/var/log/syslog, messages, auth.loglogrotatepostrotate HUP or rsyslog-rotate
Nginx/var/log/nginx/*.loglogrotateUSR1
PHP-FPMerror_log, slowlog, access loglogrotateUSR1
Laravelstorage/logsdaily channel with days, or logrotatethe app reopens per request
Go servicestderrjournaldn/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.

What "free" really means and who gets killedtotal RAM (MemTotal)anonymous memory (used)heap, stacks; only swap can free itpage cache + buffers (buff/cache)file data; reclaimed on demandfreeunused, usually smallavailable = free + reclaimable cache: the number to alert on (MemAvailable)Out of memory, step by stepallocation cannot be metno cache left to dropOOM killer scores tasksmemory share + oom_score_adjSIGKILL to the victimdmesg: "Out of memory: Killed"oom_score_adj runs from -1000 (never kill) to +1000 (kill first); a service's MemoryMax confines the kill to its own cgroup.Exit status 137 = 128 + 9: the signature of a SIGKILL, from the OOM killer, a cgroup limit or kill -9.
text
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 = 100 and 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. Size max_children from 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 MemoryMax and 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 below MemoryMax, which remains the wall.
  • A database is protected with OOMScoreAdjust=-900 so the kernel prefers to kill workers; a sacrificial job gets OOMScoreAdjust=500.
  • A VM with vm.overcommit_memory=2 refuses allocations early and apps fail with "Cannot allocate memory" while free shows plenty: the commit limit, not RAM, is the cause.
SignalWhere to see itMeaning
available low and fallingfree -m, MemAvailableReal shortage; cache is already gone
si/so non-zerovmstat 1Swapping in/out: the machine is thrashing
Result=oom-kill, exit 137systemctl status, journalA service was killed for memory
Out of memory: Killed processdmesg -T, journalctl -kThe global OOM killer
memory.events oom_kill count/sys/fs/cgroup/<unit>/memory.eventsKills inside one cgroup
memory.pressure (PSI)/proc/pressure/memoryTime 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.

bash
#!/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"
text
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                          confirm

Real 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.

MetricHealthy shapeSuspect whenTool
Load per CPUbelow 1 sustainedabove 1 for minutesuptime, /proc/loadavg
%usr + %sysheadroomnear 100 on one or all CPUsmpstat -P ALL
%walowtens of percentvmstat, iostat
%stnear 0sustained above a few percenttop, vmstat
await, aqu-szlow ms, small queuelong waits, deep queueiostat -xz
context switches csstablespikes with loadvmstat, pidstat -w
PSI some/fullnear 0rising 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.

text
"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 hold

Real 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.

QuestionCommand
My addresses and routesip -br addr, ip route
What is listeningss -ltnp, ss -lunp (UDP)
Who is connected to mess -tn state established
Does DNS answerdig +short <name>, getent hosts <name> (what applications use)
Is a remote port opennc -vz host port, curl -v telnet://host:port
Which path do packets takeip 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.

text
# /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
text
# ~/.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 10m
text
getting 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 lifetime

Real 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.

ConcernSetting or tool
Key typeEd25519 (small, fast); RSA 3072+ where required
PassphraseAlways; 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 namessh on Debian and Ubuntu, sshd on RHEL and Fedora
Per-key restrictionscommand=, from=, no-agent-forwarding in authorized_keys
Auditjournalctl -u ssh, last, lastb, /var/log/auth.log or secure
Certificatesssh-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.

text
# /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   4096
text
diagnosing "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 restart

Real 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.

WhereApplies toSet by
ulimit -nThe current shell and its childrenYou, per session
/etc/security/limits.d/*.confPAM login sessions (ssh, su, console)Administrator
LimitNOFILE= in a unit or drop-inThat serviceUnit author
DefaultLimitNOFILE= in /etc/systemd/system.confAll services without their ownAdministrator
Container runtime flags (--ulimit)One containerRuntime config
fs.file-max, fs.nr_open (sysctl)System-wide ceilingsAdministrator

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.

text
# /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).
rtcsync
text
checking 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 presentations

Real 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.

TopicDo
Server timezoneUTC
NTPchrony (or systemd-timesyncd for simple hosts); at least three sources; monitor offset
ContainersThey share the host clock; a timezone inside an image affects only formatting
ApplicationStore and compute in UTC (Go time.Time with UTC(), Laravel Carbon UTC), convert at the edge
LocaleOne explicit LANG per host and per database; avoid changing collation later
Cron or timersDocument 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 ​

text
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 time

Starting a service: the system calls behind systemctl start ​

text
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 environment

The 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 ​

KnobWhereDefault and effect
vm.swappinesssysctl, /proc/sys/vm/swappiness60; 0 to 200; higher swaps anonymous pages more readily
vm.overcommit_memorysysctl0 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_opensysctlSystem-wide and per-process descriptor ceilings
kernel.pid_maxsysctlHighest PID; a zombie leak exhausts it
net.core.somaxconnsysctlCeiling of the listen backlog
LimitNOFILE=, TasksMax=, MemoryMax=unitPer-service limits; cgroup v2 files memory.max, pids.max
DefaultTimeoutStopSec=/etc/systemd/system.confStop timeout for units without their own
SystemMaxUse=journald.confUpper bound of the journal
UMask=unitUmask of the service's processes
Storage=journald.confvolatile, persistent, auto, none

Error messages you will actually see ​

MessageMeaningFirst move
Permission deniedEACCES: a mode, ACL, capability, SELinux or AppArmor refused itnamei -l path, id, ls -ld each directory; then ausearch -m avc or dmesg
Operation not permittedEPERM: you lack a privilege (chown, binding a low port, setrlimit)Capabilities, root, NoNewPrivileges
No such file or directory on a script that existsThe interpreter in the shebang is missing (often CRLF line endings, or #!/bin/bash on Alpine)head -1 file | od -c, file script
Text file busyETXTBSY: writing to a binary that is runningWrite a new file and mv it over (atomic)
Address already in useAnother process (or a TIME-WAIT quirk) owns the portss -ltnp 'sport = :8080'
Too many open filesEMFILE (process) or ENFILE (system)/proc/<pid>/limits, LimitNOFILE=, find the leak
fork: retry: Resource temporarily unavailableEAGAIN: process or task limit, or zombiesulimit -u, TasksMax=, ps -eo stat | grep -c Z
Cannot allocate memoryENOMEM: commit limit or cgroup limitfree, vm.overcommit_memory, MemoryMax
No space left on deviceENOSPC: blocks or inodes exhausted (or quota)df -h, df -i, lsof +L1
Read-only file systemEROFS: mounted read-only or sandboxed (ProtectSystem)findmnt -o TARGET,OPTIONS, ReadWritePaths=
Failed to start ...: Start request repeated too quicklyThe start limit trippedsystemctl reset-failed, fix the crash, journalctl -u
status=203/EXECsystemd could not execve the binaryPath, execute bit, noexec mount, wrong architecture
status=217/USERThe User= does not existgetent passwd, sysusers
exit status 137 / 143SIGKILL / SIGTERMOOM 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.

go
// 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)
}
go
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
		}
	}
}
go
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)
}
go
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.

go
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.

go
// 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
}
go
// 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
}
go
// 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
}
go
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)
	}
}
text
module academy/linux-for-developers

go 1.24

The 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.

bash
#!/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"
bash
#!/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
ini
# /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
text
# /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
text
# /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
text
# /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
ini
# /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=600MiB

The 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/signal cannot catch SIGKILL or SIGSTOP (signal(7)). With Type=notify systemd waits for READY=1, so a service that fails to bind is reported at systemctl start, not minutes later.
  • Socket activation. net.FileListener on descriptor 3 (SD_LISTEN_FDS_START) after checking LISTEN_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 mode 0640 root:orders keeps secrets out of the unit and out of ps arguments; a flag value is visible in /proc/<pid>/cmdline to 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_STREAM is 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 with fstat of stderr; the service here takes the simple check). For a priority per line, prefix the line with the sd-daemon(3) level strings such as <3> (SD_ERR) or use a journald handler; plain lines are stored at priority info.
  • Memory. GOMEMLIMIT aims 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), so MemoryMax stays the wall behind it. GOMAXPROCS follows a cgroup CPU limit only from Go 1.25 ("Container-aware GOMAXPROCS" in the release notes); on older versions set it explicitly when you use CPUQuota=.
  • File descriptors and children. Close response bodies; Wait for every Start (the exitcode test 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= plus WATCHDOG=1 detects a hung process that is still "running"; /readyz (503 as soon as shutdown begins, tested) and /healthz are 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.

ini
# /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
ini
# /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=yes

The 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.

ini
# /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.target

The 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").

ini
# /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
ini
; /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 = yes

The 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
<?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 dies

The 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 why OnCalendar=*-*-* *:*:00 with AccuracySec=1s. php artisan schedule:work is the alternative for a local or container process that ticks itself.
  • Permissions. storage/ and bootstrap/cache must be writable by the user that runs PHP-FPM, the scheduler and the workers: the three units use the same User=www-data (or a dedicated shop user 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 the current symlink, php artisan migrate --force, php artisan optimize, systemctl reload php-fpm-shop (graceful SIGUSR2, so OPcache starts clean), php artisan queue:restart (workers finish their job and are restarted by Restart=always). queue:restart is Laravel's own signal to workers (stored in the cache); it replaces systemctl restart when you want graceful turnover.
  • FPM sizing. pm.max_children times the average worker RSS must fit in the memory left after the database and the OS; measure with ps. pm.max_requests recycles workers; request_terminate_timeout is the backstop for max_execution_time; slowlog finds the slow request. See Memory.
  • Sockets. listen = /run/php-fpm-shop/shop.sock with listen.owner/group/mode and the same group on the web server user; Nginx fastcgi_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 daily channel writes storage/logs/laravel-YYYY-MM-DD.log and LOG_DAILY_DAYS sets retention; stderr or syslog channels send everything to the journal and need no rotation. Pick one per environment.
  • Time. config/app.php timezone stays UTC; scheduled times and Carbon output 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).

bash
#!/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 5

The 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 ​

NeedChooseWhy
Boring server, long life, wide package setDebian stableConservative, strong security team, small, glibc
Latest tooling, LTS, cloud images, vendor supportUbuntu LTSSame base with newer userland and a commercial support option
Enterprise compliance, vendor-certified stacksRHEL or Rocky/AlmaSELinux enforcing by default, long support windows
Developer workstation tracking upstreamFedoraNew kernels and toolchains, six-month cadence
Small container images, immutable appliancesAlpine or distrolessTiny; musl and BusyBox trade-offs; no systemd
Static Go binary, no userland neededscratch or distroless staticNo distribution at all; see Images & Dockerfiles

Which filesystem and layout ​

WorkloadChoiceReason
Root volume of a general serverext4 (Debian, Ubuntu) or XFS (RHEL)The distribution default is the best-tested path
Database or large-file volumeXFS or ext4 on its own LVM or cloud volumePredictable 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, compressionBtrfs, or ZFS where licensing allowsCopy-on-write features
Ephemeral scratchtmpfsRAM-fast, gone at reboot
Shared between hostsNFS or object storage, not for databasesLatency, locking and D-state hangs

Which scheduler for a recurring job ​

SituationChoice
Logs, limits, catch-up after downtime, per-run exit statussystemd timer plus a oneshot service
One trivial job on a host you already manage with croncron
A fleet where jobs must run once somewhereApplication-level lock (onOneServer) or Kubernetes CronJob, not one cron per host
Sub-minute or event-drivenA long-running service or a queue worker, not cron
Laravel tasksOne schedule:run tick per minute (timer), tasks defined in code

Which place for logs ​

SourceChoice
Go service you writestderr, 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
Laravelstderr channel in containers, daily with retention on VMs
Anything you must keep or search after the host is goneShip 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 ​

ScaleWhat changes in the Linux layer
1x: one VMHand-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 balancerUnits 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 fleetImmutable 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
BeyondKubernetes 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) ​

bash
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 directory

Expected 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) ​

bash
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 $?"                 # 3

Observed 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.

bash
(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 sym

Observed: -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) ​

bash
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-api

5. Install and run the service (expected, not run) ​

bash
(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 default

6. Reload, stop and the exit status (expected, not run) ​

bash
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=signal

7. Timers, logs, limits and memory (expected, not run) ​

bash
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 file

8. Break it on purpose (expected, not run) ​

bash
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 ​

BeliefReality
Linux is an operating systemIt is the kernel; distributions add the userland, and containers share only the kernel
kill kills a processIt sends SIGTERM by default, which the program may handle; only SIGKILL and SIGSTOP are uncatchable
A zombie is a stuck process I can kill -9It is already dead; only its parent's wait (or the parent's exit) removes it
Free memory should be largeUnused RAM is wasted; watch available and swap activity, not free
Load average is CPU usageIt counts runnable plus uninterruptible tasks over damped 1/5/15-minute windows; compare it with the CPU count
chmod 777 fixes permissionsIt removes them; find the directory without x with namei -l and fix owner or group
If the group may write, the owner may tooOne class applies: owner, else group, else other; the owner class can deny what the others allow
sudo makes my shell rootIt runs one command as another user and logs it
Binding port 80 needs rootIt needs CAP_NET_BIND_SERVICE, or socket activation, or a proxy on port 80
rm frees disk spaceIt removes a name; space returns when the last link and the last open descriptor go
df and du must agreeThey measure different things; the difference is deleted-but-open files, hidden mounts, sparse files and snapshots
Editing limits.conf raises a service's limitsThat file is for PAM login sessions; services use LimitNOFILE=
Restart=always makes a service reliableIt hides crashes and loops; use on-failure, RestartSec and a start limit, and alert on NRestarts
network.target means the network is upIt means the stack is up; use network-online.target when you need an address
Cron is enough everywhereIt is fine for trivial jobs; timers add logs, limits, overlap control and catch-up
Set servers to the local timezoneUse UTC and convert at the edge; local time duplicates and skips an hour

Cheat sheet ​

TopicRemember
Kernel vs userlandOne kernel, many userlands; containers share the host kernel; /etc/os-release names the distribution
Packagesapt (Debian, Ubuntu), dnf (RHEL, Fedora), apk (Alpine); update refreshes the index, upgrade installs; owner of a file: dpkg -S, rpm -qf
ProcessesPID, PPID, fork then exec; ps -eo pid,ppid,user,stat,cmd; /proc/<pid>/ has the truth
StatesR, S, D (disk wait, immune to signals), T, Z (needs parent's wait)
SignalsTERM 15 polite, KILL 9 final, HUP 1 reload, INT 2 Ctrl+C, QUIT 3 dump; exit 137 = KILL, 143 = TERM
UsersNumbers matter, names are labels; one system user per service, nologin; id, getent
ModesOctal 4/2/1 per owner, group, other; one class decides; umask clears bits (0666 & ~022 = 0644); X capital for directories
Specialsetuid 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
Diskdf -h, df -i, du -xh, lsof +L1, lsblk -f, findmnt; mount by UUID with nofail
systemdsystemctl status/cat/edit/daemon-reload, journalctl -u X -f, systemd-analyze verify/security
UnitUser=, Type=notify, Restart=on-failure, TimeoutStopSec, EnvironmentFile, StateDirectory, MemoryMax, NoNewPrivileges, ProtectSystem=strict
TimersOnCalendar, Persistent=true, RandomizedDelaySec; systemctl list-timers
Logsstderr to journald; journalctl -p err -b; logrotate needs a reopen signal; bound the journal
Memoryavailable not free; OOM kills by score plus oom_score_adj; MemoryMax scopes it; dmesg -T shows the kill
LoadCompare with CPU count; vmstat 1, iostat -xz 1, mpstat -P ALL, sar; st = hypervisor steal
Networkip -br addr, ss -ltnp, dig +short, getent hosts
SSHEd25519 keys, IdentitiesOnly, ProxyJump, PermitRootLogin no, PasswordAuthentication no, sshd -t before reload
Limitsulimit -n is shell-only; services use LimitNOFILE=; check /proc/<pid>/limits
TimeUTC, chrony, timedatectl, chronyc tracking

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
KernelThe privileged core that schedules processes, manages memory, drivers, filesystems and permissions
UserlandEverything outside the kernel: shell, libraries, tools, init system
DistributionA packaged combination of kernel, userland, package manager and release policy
glibc / muslThe two common C libraries on Linux; Alpine uses musl
Package managerTool that installs, upgrades and removes signed packages (apt, dnf, apk)
RepositoryA signed collection of packages and an index served over HTTP
ProcessA running program instance with PID, memory, descriptors and credentials
PID / PPIDProcess ID and its parent's ID; PID 1 is init
fork / execDuplicate the calling process / replace its program image
ZombieA terminated process whose exit status has not yet been read by its parent
OrphanA live process whose parent died; adopted by PID 1 or a subreaper
SignalAn asynchronous notification delivered to a process (SIGTERM, SIGKILL, SIGHUP ...)
Exit statusThe number a process returns; 128 + n for death by signal n in a shell
NicenessScheduling weight from -20 to 19; higher means more polite
/procPseudo-filesystem exposing kernel and process state as files
UID / GIDNumeric user and group identities the kernel checks
Effective / saved UIDThe identity used for checks / the copy kept by setuid programs
ModePermission bits (rwx for owner, group, other) plus setuid, setgid, sticky
umaskBits removed from the mode of newly created files and directories
setuid / setgidRun an executable with its owner's or group's identity
Sticky bitOn a directory: only the owner of an entry may delete or rename it
ACLAccess control list: named users and groups on top of the mode bits
CapabilityOne privilege split out of root (for example CAP_NET_BIND_SERVICE)
FHSFilesystem Hierarchy Standard: what lives in /etc, /var, /usr, /opt, /tmp
MountAttaching a filesystem at a directory
fstabFile listing filesystems to mount at boot
InodeRecord holding a file's metadata and block pointers, not its name
Hard link / symlinkA second name for an inode / a file containing a path
LVMLogical Volume Manager: physical volumes, volume groups, logical volumes
SwapDisk space used as overflow for memory pages
systemdPID 1 service manager with units, dependencies, cgroups and a journal
UnitConfiguration object systemd manages (service, timer, socket, target, mount ...)
TargetA unit grouping others into a boot or runtime state
Drop-inA .d/*.conf file that overrides parts of a unit
Socket activationsystemd binds the socket and starts the service on the first connection
Type=notifyUnit type that waits for the program to send READY=1
cgroupKernel group of processes with resource limits and accounting
Journal / journaldsystemd's structured log store and collector
rsyslogClassic syslog daemon writing text logs and forwarding them
logrotateTool that rotates, compresses and prunes log files
Page cacheRAM used to cache file contents; reclaimable
OOM killerKernel mechanism that kills a process when memory cannot be reclaimed
oom_score_adjPer-process offset (-1000 to +1000) added to the OOM badness score
Load averageExponentially damped count of runnable plus uninterruptible tasks over 1, 5, 15 minutes
CPU stealTime a virtual CPU waited because the hypervisor ran another guest
PSIPressure Stall Information: time tasks spent stalled on CPU, memory or I/O
File descriptorSmall integer naming an open file, socket or pipe in a process
rlimit / ulimitPer-process resource limits (soft and hard)
chronyNTP implementation that keeps the system clock accurate
NTPNetwork Time Protocol
LocaleLanguage and formatting settings (LANG, LC_*)
SSH key pairPublic and private key used instead of a password
sshdThe SSH server daemon
Bastion / ProxyJumpA host used to reach private hosts; the SSH option that hops through it
Service userA non-login system account that owns one service's process and files
EnvironmentFileUnit setting that loads KEY=value lines into the service environment
PHP-FPMFastCGI process manager that runs PHP workers behind a web server

References ​

Built by Morteza Negahi