TExcelTAD

init & systemd

When the kernel has mounted the root file system, it starts exactly one user-space program: init, process ID 1. Every other process on the system is its descendant. PID 1 has three jobs: start everything the system needs, supervise it while it runs, and shut it all down cleanly. On almost every mainstream distribution today (Ubuntu, Debian, Fedora, RHEL, Arch, openSUSE) that program is systemd.

From SysV init to systemd

SysV init (until ~2014) systemd
Configuration Shell scripts in /etc/init.d/ Declarative unit files
Ordering Numbered symlinks S20ssh, S30cron per runlevel Dependencies (After=, Requires=, Wants=)
Start-up One script after another In parallel, as soon as dependencies are met
Supervision None: a crashed daemon stays dead Restarts services by policy, tracks every process in a cgroup
Logs Each daemon writes its own file under /var/log Central journal (journalctl) plus optional syslog
States Runlevels 0–6 Targets (multi-user.target, graphical.target)

Alpine (this course's sandbox) uses OpenRC, Void uses runit, and containers usually have no init at all: the main program is PID 1. Everything below assumes a normal systemd machine, so the commands are shown as sample sessions.

Units

systemd manages units. Each is described by a small INI-style file; the suffix says what kind it is:

Unit type Manages Example
.service A process / daemon ssh.service, nginx.service
.socket A listening socket; starts the service on the first connection cups.socket
.timer Time-based activation (the modern cron) fstrim.timer
.target A group of units, a synchronisation point multi-user.target
.mount, .automount A mount point (generated from /etc/fstab) home.mount
.path Starts a unit when a file or directory changes cups.path
.device A kernel device, from udev dev-sda.device
.slice, .scope cgroup groups for resource limits user.slice

Unit files are looked up in three places, the later overriding the earlier: /usr/lib/systemd/system/ (shipped by packages, don't edit), /run/systemd/system/ (runtime) and /etc/systemd/system/ (yours).

A service for a small web app could look like this (/etc/systemd/system/notely.service):

ini
[Unit]
Description=Notely web app
After=network-online.target postgresql.service
Wants=network-online.target
Requires=postgresql.service

[Service]
Type=simple
User=notely
WorkingDirectory=/opt/notely
ExecStart=/opt/notely/bin/server --port 8080
Restart=on-failure
RestartSec=2
Environment=NOTELY_ENV=production
# hardening: a private /tmp, read-only /usr and /etc, no privilege escalation
PrivateTmp=yes
ProtectSystem=strict
NoNewPrivileges=yes

[Install]
WantedBy=multi-user.target

Note the difference between the two dependency kinds: Requires=/Wants= say what must also be started (strong / weak), while After= says in which order. They are independent: Requires= without After= starts both at the same time.

How systemd orders the boot

At boot systemd starts from the default target and walks the dependencies backwards, then starts every unit whose After= units are already up, in parallel "waves". This program performs the same calculation for a small set of units:

python · try it yourself
units = {   # unit: (pulled in by Wants/Requires, ordered After)
    "multi-user.target":     (["sshd.service", "notely.service", "cron.service"], ["basic.target"]),
    "basic.target":          (["sysinit.target"], ["sysinit.target"]),
    "sysinit.target":        (["local-fs.target", "systemd-journald.service"], ["local-fs.target", "systemd-journald.service"]),
    "local-fs.target":       ([], []),
    "systemd-journald.service": ([], []),
    "network-online.target": ([], ["basic.target"]),
    "postgresql.service":    ([], ["basic.target"]),
    "sshd.service":          ([], ["basic.target"]),
    "cron.service":          ([], ["basic.target"]),
    "notely.service":        (["postgresql.service", "network-online.target"],
                              ["basic.target", "postgresql.service", "network-online.target"]),
}

def closure(target):                      # everything the target pulls in
    seen, todo = set(), [target]
    while todo:
        u = todo.pop()
        if u not in seen:
            seen.add(u)
            todo.extend(units[u][0] + units[u][1])
    return seen

def after(u):                             # a target is implicitly ordered after what it pulls in
    pulls, order = units[u]
    return order + (pulls if u.endswith(".target") else [])

def boot(target):
    pending, started, wave = closure(target), set(), 0
    while pending:
        ready = sorted(u for u in pending if all(a in started for a in after(u) if a in pending | started))
        wave += 1
        print(f"wave {wave}: {', '.join(ready)}")
        started |= set(ready)
        pending -= set(ready)

boot("multi-user.target")
wave 1: local-fs.target, systemd-journald.service
wave 2: sysinit.target
wave 3: basic.target
wave 4: cron.service, network-online.target, postgresql.service, sshd.service
wave 5: notely.service
wave 6: multi-user.target

Four units start together in wave 4; only notely waits for its database, and the target is reached last. (systemd adds that implicit ordering itself: a target is ordered after the units it wants.) Real systemd also uses socket activation: it creates the listening sockets itself before any service starts, so even services that talk to each other can start simultaneously.

systemctl: controlling units

bash
ada@ubuntu:~$ systemctl status ssh
● ssh.service - OpenBSD Secure Shell server
     Loaded: loaded (/usr/lib/systemd/system/ssh.service; enabled; preset: enabled)
     Active: active (running) since Mon 2026-10-12 08:14:03 UTC; 5 days ago
   Main PID: 1123 (sshd)
      Tasks: 1 (limit: 18898)
     Memory: 6.2M (peak: 9.8M)
        CPU: 1.204s
     CGroup: /system.slice/ssh.service
             └─1123 "sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"
ada@ubuntu:~$ sudo systemctl restart ssh
ada@ubuntu:~$ sudo systemctl enable --now notely
Created symlink /etc/systemd/system/multi-user.target.wants/notely.service → /etc/systemd/system/notely.service.
ada@ubuntu:~$ systemctl list-units --type=service --state=failed
  UNIT           LOAD   ACTIVE SUB    DESCRIPTION
● notely.service loaded failed failed Notely web app

(Sample output; yours will differ.)

Command Effect
systemctl start / stop / restart X Change the state now
systemctl reload X Ask the service to re-read its config without restarting
systemctl enable / disable X Start (or not) at boot: creates/removes the .wants/ symlink from [Install]
systemctl enable --now X Both at once
systemctl mask X Make it impossible to start (links it to /dev/null)
systemctl daemon-reload Re-read unit files after you edit them
systemctl edit X Create a drop-in override in /etc/systemd/system/X.service.d/
systemctl get-default, set-default The boot target
systemctl isolate rescue.target Switch to another target (like changing runlevel)
systemctl --user … Your own per-user services, no root needed

"Enabled" and "active" are independent: a service can be running but not enabled (it won't come back after a reboot), or enabled but stopped.

Supervision and restart policies

Because systemd placed each service in its own cgroup, it knows every process that belongs to it (even double-forked daemons) and notices when the main process dies. Then Restart= decides what happens, and a rate limit stops a crash loop:

python · try it yourself
def supervise(exit_codes, restart="on-failure", burst=3):
    starts = 0
    for code in exit_codes:
        starts += 1
        if starts > burst:
            print("start request repeated too quickly -> unit enters 'failed' state")
            return
        state = "exited cleanly" if code == 0 else f"failed with status {code}"
        print(f"start #{starts}: main process {state}")
        if restart == "no" or (restart == "on-failure" and code == 0):
            print("not restarting (Restart=%s)" % restart)
            return
        print("  scheduling restart in 2 s (RestartSec=2)")
    print("still running")

supervise([1, 1, 1, 1, 1])          # keeps crashing
print("---")
supervise([1, 0])                   # crashes once, then exits normally
print("---")
supervise([1], restart="no")
start #1: main process failed with status 1
  scheduling restart in 2 s (RestartSec=2)
start #2: main process failed with status 1
  scheduling restart in 2 s (RestartSec=2)
start #3: main process failed with status 1
  scheduling restart in 2 s (RestartSec=2)
start request repeated too quickly -> unit enters 'failed' state
---
start #1: main process failed with status 1
  scheduling restart in 2 s (RestartSec=2)
start #2: main process exited cleanly
not restarting (Restart=on-failure)
---
start #1: main process failed with status 1
not restarting (Restart=no)

The real defaults are StartLimitBurst=5 within StartLimitIntervalSec=10s; after that, systemctl reset-failed X clears the counter.

Targets instead of runlevels

SysV runlevel systemd target Meaning
0 poweroff.target Shut down
1 rescue.target Single user, root shell, basic system
3 multi-user.target Full system, text login, network
5 graphical.target multi-user plus the display manager
6 reboot.target Reboot
— emergency.target Root shell with only the root file system, read-only

The journal

systemd-journald collects everything a service writes to stdout/stderr, plus syslog messages and the kernel log, in a structured, indexed binary journal (/var/log/journal/):

bash
ada@ubuntu:~$ journalctl -u notely --since today -n 5
Oct 17 09:02:11 ubuntu systemd[1]: Started notely.service - Notely web app.
Oct 17 09:02:12 ubuntu server[48211]: listening on :8080
Oct 17 09:40:57 ubuntu server[48211]: panic: connection refused (postgresql)
Oct 17 09:40:57 ubuntu systemd[1]: notely.service: Main process exited, code=exited, status=2/INVALIDARGUMENT
Oct 17 09:40:57 ubuntu systemd[1]: notely.service: Failed with result 'exit-code'.
ada@ubuntu:~$ journalctl -b -p err        # errors from this boot only
ada@ubuntu:~$ journalctl -f               # follow live, like tail -f
ada@ubuntu:~$ journalctl --disk-usage
Archived and active journals take up 1.1G in the file system.

(Sample output.) On Windows the equivalents are the Service Control Manager and the Event Log: see Windows Services. For scheduled jobs with timers see Bash: cron & systemd.

Learn more: The Linux Boot Process · Bash: cron & systemd · Windows Services

Test yourself

What is the difference between Requires= and After= in a unit file?

  1. They are synonyms
  2. Requires= pulls the other unit in; After= only sets the start order
  3. After= pulls the unit in; Requires= sets the order
  4. Requires= is for targets only

A service runs now, but disappears after every reboot. What did you forget?

  1. systemctl start
  2. systemctl enable
  3. systemctl daemon-reload
  4. systemctl mask

Which systemd target corresponds to the old runlevel 3 (text mode, networking, multi-user)?

  1. rescue.target
  2. multi-user.target
  3. graphical.target
  4. basic.target