8.1. Understanding Systemd Units

systemd runs as PID 1 and keeps a list of units: named objects it can activate, stop, and observe. A unit's definition is a file with sections such as [Unit], [Service], and [Install]; the file's suffix says what kind of object it describes. Administrators mostly touch four kinds:

Unit type What it represents
.service A process or one-shot job: a daemon, a script, an application
.socket A socket systemd holds so the service behind it can start on demand
.target A synchronization point that groups other units for boot ordering
.path A watched file or directory whose changes trigger a service

Three more appear throughout the book without needing this chapter's attention: .timer units schedule work (Chapter 10), .mount units represent filesystems (Chapter 7), and .slice/.scope units group processes for resource control (Chapter 9).

8.1.1. Services, Sockets, Targets, Paths, and Dependencies

On client1, in john's shell, list the services that are currently running:

$ systemctl list-units --type=service --state=running --no-legend --no-pager
  chrony.service           loaded active running chrony, an NTP client/server
  cron.service             loaded active running Regular background program processing daemon
  dbus.service             loaded active running D-Bus System Message Bus
  getty@tty1.service       loaded active running Getty on tty1
  rsyslog.service          loaded active running System Logging Service
  ssh.service              loaded active running OpenBSD Secure Shell server
  systemd-journald.service loaded active running Journal Service
  systemd-logind.service   loaded active running User Login Management
  systemd-machined.service loaded active running Virtual Machine and Container Registration Service
  systemd-udevd.service    loaded active running Rule-based Manager for Device Events and Files
  user@1000.service        loaded active running User Manager for UID 1000

list-units reads the manager's live state, not the disk: these units are loaded and active right now. --no-legend drops the summary footer and --no-pager sends the listing to the terminal instead of opening a pager. The last line is the per-user manager of a logged-in account, described in Section 8.1.3. To see what exists on disk regardless of current state, list unit files and their enablement state:

$ systemctl list-unit-files --type=service --no-pager | grep -E "^(ssh|rsyslog|cron)\.service"
cron.service                                 enabled         enabled
rsyslog.service                              enabled         enabled
ssh.service                                  enabled         enabled

The pipeline feeds the full listing through grep, which keeps only the three lines whose unit names begin with ssh, rsyslog, or cron. Each line shows two states: the first column is the local enablement (Section 8.2.2), the second is what the distribution's preset policy would do. The boot process ends at a default target:

$ systemctl get-default
graphical.target

graphical.target pulls in multi-user.target, which in turn wants the multi-user services such as SSH; a server without a desktop is typically set to multi-user.target with systemctl set-default, as described in Chapter 7. Targets in the loaded state:

$ systemctl list-units --type=target --no-legend --no-pager
  basic.target        loaded active active Basic System
  getty.target        loaded active active Login Prompts
  graphical.target    loaded active active Graphical Interface
  local-fs-pre.target loaded active active Preparation for Local File Systems
  local-fs.target     loaded active active Local File Systems
  machines.target     loaded active active Containers
  multi-user.target   loaded active active Multi-User System
  network.target      loaded active active Network
  paths.target        loaded active active Path Units
  remote-fs.target    loaded active active Remote File Systems
  slices.target       loaded active active Slice Units
  sockets.target      loaded active active Socket Units
  swap.target         loaded active active Swaps
  sysinit.target      loaded active active System Initialization
  timers.target       loaded active active Timer Units

A target is active when its members have been dealt with, not when a process runs; that is why every target here shows active rather than running. Sockets are the other structural piece - systemd holds the listening socket itself and starts the service behind it only when the first connection arrives:

$ systemctl list-units --type=socket --no-legend --no-pager
  dbus.socket                     loaded active running   D-Bus System Message Bus Socket
  sshd-unix-local.socket          loaded active listening OpenSSH Server Socket (systemd-ssh-generator, AF_UNIX Local)
  syslog.socket                   loaded active running   Syslog Socket
  systemd-coredump.socket         loaded active listening Process Core Dump Socket
  systemd-creds.socket            loaded active listening Credential Encryption/Decryption
  systemd-hostnamed.socket        loaded active listening Hostname Service Socket
  systemd-initctl.socket          loaded active listening initctl Compatibility Named Pipe
  systemd-journald-dev-log.socket loaded active running   Journal Socket (/dev/log)
  systemd-journald.socket         loaded active running   Journal Sockets
  systemd-sysext.socket           loaded active listening System Extension Image Management
  systemd-udevd-control.socket    loaded active running   udev Control Socket
  systemd-udevd-kernel.socket     loaded active running   udev Kernel Socket

syslog.socket is the reason a stopped logging daemon does not lose messages: the socket stays open and the daemon reads from it when it comes back. Dependencies tie all of this together. ssh.service declares what it needs, and the manager resolves the order:

$ systemctl list-dependencies ssh.service --no-pager
ssh.service
● ├─-.mount
○ ├─sshd-keygen.service
● ├─system.slice
● └─sysinit.target
●   ├─apparmor.service
●   ├─dev-hugepages.mount
●   ├─dev-mqueue.mount
●   ├─kmod-static-nodes.service
●   ├─ldconfig.service
●   ├─proc-sys-fs-binfmt_misc.automount
●   ├─sys-fs-fuse-connections.mount
●   ├─sys-kernel-config.mount
●   ├─sys-kernel-debug.mount
●   ├─sys-kernel-tracing.mount
●   ├─systemd-ask-password-console.path
●   ├─systemd-binfmt.service
○   ├─systemd-firstboot.service

Selected output; about forty further lines list the rest of the system initialization and local filesystem units that sysinit.target pulls in. A filled circle marks a unit that is currently active; a hollow circle marks one that is loaded but not active - for example sshd-keygen.service already did its one-time work and exited. The raw dependency properties behind the tree are readable directly:

$ systemctl show -p Id -p Requires -p Wants -p After ssh.service
Id=ssh.service
Requires=sysinit.target -.mount system.slice
Wants=sshd-keygen.service
After=-.mount network.target system.slice sysinit.target auditd.service basic.target nss-user-lookup.target systemd-journald.socket sshd-keygen.service

Three dependency families matter in practice. Requires= is hard: if the listed unit fails, this unit fails too. Wants= is best effort: the listed unit is started, but its failure does not propagate. Neither of them orders anything by itself - After= does the ordering, which is why nearly every well-written unit combines Wants= or Requires= with After=. Figure 8.1 summarizes the model.

Relationships between targets, sockets, paths, and services

Figure 8.1. Conceptual view of the unit model. Targets group services for boot; sockets hand their first connection to a service; path units trigger a oneshot service when a watched file changes. Requires=, Wants=, and After= connect the pieces.

Path units complete the set. The following example watches a file and runs a short service when it changes. As root on client1, create the watched directory:

# install -d /var/lib/handbook-heartbeat

The command creates the directory with default ownership and mode and produces no output. Contents of /etc/systemd/system/handbook-watch.path:

[Unit]
Description=Watch for the handbook trigger file

[Path]
PathChanged=/var/lib/handbook-heartbeat/trigger
Unit=handbook-path.service

[Install]
WantedBy=paths.target

Contents of /etc/systemd/system/handbook-path.service:

[Unit]
Description=Handbook path unit trigger

[Service]
Type=oneshot
ExecStart=/usr/bin/logger -t handbook-path "trigger file appeared"

PathChanged= fires whenever the watched file is closed after a change; PathExists= and PathModified= are the nearby variants (systemd.path(5) lists them all). Unit= names the service to start, and the triggered service is a Type=oneshot job that runs one command and exits. Load the new definitions and start the watch:

# systemctl daemon-reload

daemon-reload re-reads unit files from disk; it prints nothing and does not restart anything. Starting a unit is equally silent:

# systemctl start handbook-watch.path

From john's shell, confirm the watch is loaded and active:

$ systemctl list-units --type=path --no-legend --no-pager
  handbook-watch.path               loaded active waiting Watch for the handbook trigger file
  systemd-ask-password-console.path loaded active waiting Dispatch Password Requests to Console Directory Watch
  systemd-ask-password-wall.path    loaded active waiting Forward Password Requests to Wall Directory Watch

The path unit is waiting, not running - it is armed. As root, create the trigger file, then read what the triggered service wrote:

# touch /var/lib/handbook-heartbeat/trigger
# journalctl -t handbook-path -n 5 --no-pager
Nov 19 08:41:23 client1 handbook-path[57281]: trigger file appeared
Nov 19 08:58:02 client1 handbook-path[63998]: trigger file appeared

The -t option selects records by syslog identifier, which is how the logger command signed its message. The journal holds one entry per run of the exercise; the earlier line is from a previous trigger of the same watch. A -u filter would not find this message: journalctl -u handbook-path.service selects records by the unit the process ran under, and a short oneshot logger process records no unit of its own. When the watch is no longer wanted, stop it and remove the trigger:

# systemctl stop handbook-watch.path
# rm -f /var/lib/handbook-heartbeat/trigger

Both commands complete silently.

8.1.2. Unit Search Paths, Vendor Files, and Local Overrides

systemd looks for unit files in a fixed list of directories and uses the first file it finds for a given name:

$ systemd-analyze unit-paths
/etc/systemd/system.control
/run/systemd/system.control
/run/systemd/transient
/run/systemd/generator.early
/etc/systemd/system
/etc/systemd/system.attached
/run/systemd/system
/run/systemd/system.attached
/run/systemd/generator
/usr/local/lib/systemd/system
/usr/lib/systemd/system
/run/systemd/generator.late

The order is the whole point. /usr/lib/systemd/system holds the units Debian packages ship; /usr/local/lib/systemd/system holds units installed by locally built software; /run/systemd/system holds volatile runtime units; and /etc/systemd/system belongs to the administrator. A file in /etc with the same name as a vendor file shadows it completely - the vendor file is ignored, not merged. The generator directories are filled at boot by tools that translate other configuration into units. Figure 8.2 shows the layers an administrator works with.

Unit search paths and drop-in merging

Figure 8.2. Conceptual view of unit lookup. Same-named files in higher layers shadow lower ones; drop-in files under unit-name.service.d/ are merged on top of whichever file wins.

Shadowing wholesale is rarely what you want, because a package upgrade improves the vendor file while the shadow copy goes stale. The preferred mechanism is the drop-in: a file under /etc/systemd/system/name.service.d/*.conf whose keys are merged over the unit file. systemctl cat shows the effective unit - every fragment, in order:

$ systemctl cat ssh.service
# /usr/lib/systemd/system/ssh.service
[Unit]
Description=OpenBSD Secure Shell server
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target nss-user-lookup.target auditd.service
ConditionPathExists=!/etc/ssh/sshd_not_to_be_run

[Service]
EnvironmentFile=-/etc/default/ssh
ExecStartPre=/usr/sbin/sshd -t
ExecStart=/usr/sbin/sshd -D $SSHD_OPTS
ExecReload=/usr/sbin/sshd -t
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartPreventExitStatus=255
Type=notify
RuntimeDirectory=sshd
RuntimeDirectoryMode=0755

[Install]
WantedBy=multi-user.target
Alias=sshd.service

# /etc/systemd/system/ssh.service.d/generate-ssh-keys.conf
[Service]
# remove existing ExecStartPre
ExecStartPre=
ExecStartPre=/usr/local/sbin/vagrant-generate-ssh-host-keys
# re-add existing ExecStartPre line (this one must be run after the generation of keys)
ExecStartPre=/usr/sbin/sshd -t

The first fragment is the vendor unit from the openssh-server package; a plain Debian installation shows only that fragment. The second is a local drop-in on the system used for the examples, installed when its image was built, and it demonstrates the one pattern that trips people up: list directives such as ExecStart= and ExecStartPre= are cumulative across fragments, so a drop-in that wants to insert its own command first must reset the list with an empty assignment (ExecStartPre= on a line of its own) and then re-add the vendor's command afterwards. Single-value keys such as Restart= or Type= simply take the last value read. Drop-ins sort by filename, so numeric prefixes (10-...conf, 20-...conf) make the evaluation order visible.

One more layer exists for completeness: .wants/ and .requires/ directories next to a unit hold symlinks that create dependencies. Enabling a service, covered in Section 8.2.2, is nothing more than creating such a symlink under multi-user.target.wants/.

8.1.3. System Units and User Units

Everything above runs under the system manager (PID 1). Each logged-in user also gets a user manager - the user@UID.service entry in the system listing - which runs a private instance of systemd for that account and manages units stored under ~/.config/systemd/user/. The same verbs apply with systemctl --user, and the same search-path logic holds, with ~/.config/systemd/user playing the role of /etc/systemd/system.

A user manager normally lives only as long as its owner has at least one session. A service that must keep running - an agent, a personal daemon - needs lingering, which starts the user manager at boot and keeps it after logout. As root on client1:

# loginctl enable-linger john

The command is silent. From john's shell, the state is visible:

$ loginctl show-user john -p Linger
Linger=yes

The user unit below writes its log file into john's workspace, so create that first, from john's shell on client1:

$ mkdir -p ~/debian-handbook/services-logs

Also silent. To exercise the whole path, john runs a small heartbeat under his own manager. Its script, installed by root as /usr/local/bin/handbook-user-tick, prints a timestamped line and appends it to a file in that workspace:

#!/bin/sh
while true; do
    stamp="$(date --iso-8601=seconds)"
    printf '%s user-service tick\n' "$stamp"
    printf '%s user-service tick\n' "$stamp" \
        >> "$HOME/debian-handbook/services-logs/user-heartbeat.log"
    sleep 5
done

Contents of ~/.config/systemd/user/handbook-user.service, written by john:

[Unit]
Description=Handbook user heartbeat

[Service]
Type=simple
WorkingDirectory=%h/debian-handbook/services-logs
ExecStart=/usr/local/bin/handbook-user-tick
Restart=on-failure

[Install]
WantedBy=default.target

%h expands to the user's home directory; %u and %I are the nearby specifiers for the user name and the instance name in template units. The user manager's default target is default.target, the user-level equivalent of the system's boot targets. Make the script executable as root before it is first run:

# chmod 755 /usr/local/bin/handbook-user-tick

In a login session as john - over SSH, following the login procedure in Chapter 20 - load the unit and enable it:

$ systemctl --user daemon-reload
$ systemctl --user enable --now handbook-user.service
Created symlink '/home/john/.config/systemd/user/default.target.wants/handbook-user.service' → '/home/john/.config/systemd/user/handbook-user.service'.

enable --now does both jobs at once: it creates the wants symlink in default.target.wants and starts the unit. Its state, still from john's session:

$ systemctl --user status handbook-user.service --no-pager
● handbook-user.service - Handbook user heartbeat
     Loaded: loaded (/home/john/.config/systemd/user/handbook-user.service; enabled; preset: enabled)
     Active: active (running) since Thu 2026-11-19 08:58:16 UTC; 1s ago
 Invocation: edfc35ff346346aeb17fe548c6eb816f
      Main PID: 64144 (handbook-user-t)
      Tasks: 2 (limit: 806)
      Memory: 408K (peak: 1.7M)
        CPU: 9ms
      CGroup: /user.slice/user-1001.slice/user@1001.service/app.slice/handbook-user.service
             ├─64144 /bin/sh /usr/local/bin/handbook-user-tick
             └─64148 sleep 5

Nov 19 08:58:16 client1 systemd[64060]: Started handbook-user.service - Handbook user heartbeat.
Nov 19 08:58:16 client1 handbook-user-tick[64144]: 2026-11-19T08:58:16+00:00 user-service tick

The cgroup line shows the nesting: the unit runs inside john's user manager (user@1001.service), which itself runs under the system manager. The machine-readable form of the same facts:

$ systemctl --user show -p ActiveState -p SubState -p MainPID handbook-user.service
MainPID=64144
ActiveState=active
SubState=running

The user unit's own records are readable with --user-unit:

$ journalctl --user-unit handbook-user.service -n 5 --no-pager
Nov 19 08:58:16 client1 systemd[64060]: Started handbook-user.service - Handbook user heartbeat.
Nov 19 08:58:16 client1 handbook-user-tick[64144]: 2026-11-19T08:58:16+00:00 user-service tick
Nov 19 08:58:21 client1 handbook-user-tick[64144]: 2026-11-19T08:58:21+00:00 user-service tick
Hint: You are currently not seeing messages from the system.
      Users in groups 'adm', 'systemd-journal' can see all messages.
      Pass -q to turn off this notice.

Selected output; two older entries from a previous run of the same unit were omitted. The hint at the bottom is journalctl itself explaining the access model: a user sees only the records the access rules grant, and the groups named in the hint unlock the rest of the journal. Section 8.4.3 returns to this in detail. With lingering on, john could log out and the heartbeat would keep running; to retire the example instead, disable and stop it from john's session, and turn lingering off as root:

$ systemctl --user disable --now handbook-user.service
Removed '/home/john/.config/systemd/user/default.target.wants/handbook-user.service'.
# loginctl disable-linger john