Module 1 · Lesson 46 of 103

systemd units and services

Use systemctl to inspect units, manage services, select targets, and write a foreground script service with explicit configuration and restart behavior.

  • Beginner to advanced
  • 7 min read
  • 14 min lab
What you will need

Ubuntu 24.04 VM with systemd, sudo and console access; an optional ARM board with a recoverable boot image

Your place in the module
By the end you can 3 objectives
  • Use systemctl to inspect units, manage services and select targets.
  • Create a foreground script service with explicit configuration and restart behavior.
  • Locate a unit's effective configuration and apply an override without copying the vendor definition.
Video coming soonsystemd units and services
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from From power to initramfs
  • Firmware, loaders, the kernel and early userspace have different responsibilities.
  • An initramfs supplies the tools and drivers needed to reach the real root filesystem.
  • The kernel command line configures the kernel and early userspace; the loader's own root selection is separate from Linux's root= setting.
01

Units, service management and operating targets

4 min read

The previous lesson followed control from power-on through initramfs to PID 1. This lesson answers how systemd units, services and operating targets manage that system.

For example, a service unit's file can exist without its program running. The suffix identifies the unit type. Each unit has configuration, a loading state and a runtime state. The table shows the main types; a socket is a communication endpoint, and a timer schedules activation.

Type Role
.service Run and supervise a program or a finite task.
.target Group units and provide synchronization points.
.socket Hold a communication endpoint and activate a matching service.
.timer Activate another unit according to a schedule.
.mount Manage a filesystem mounted at a particular path.
.device Represent a kernel device exposed through device management.

/data maps to data.mount: mount unit names encode paths. Device units normally appear dynamically from device information, rather than administrator-written files. systemd can generate mount units from /etc/fstab too. For a failed mount, inspect both the unit and the configuration that produced it.

An administrator file in /etc/systemd/system/ overrides a same-named vendor unit. Vendor files normally live in /usr/lib/systemd/system/. Some distributions use /lib/systemd/system/, which may resolve there through merged directories. Runtime overrides in /run/systemd/system/ disappear at reboot. These directories are important parts of the unit search path, not the complete list. Inspect loaded services, installed files and journald's configuration sources:

bash
systemctl list-units --type=service --all
systemctl list-unit-files --type=service
systemctl cat systemd-journald.service
systemctl show systemd-journald.service -p FragmentPath -p DropInPaths

list-units shows what the manager has loaded; --all includes inactive units. list-unit-files lists installed unit files and their enablement states. cat shows source fragments and drop-ins. A fragment is a unit's main configuration file; a drop-in adds small overrides. show reads the manager's properties. Create a drop-in with systemctl edit name.service to avoid copying a whole vendor definition.

Ordinary unit override precedence/etc/systemd/systemAdministrator overrides/run/systemd/systemRuntime overrides/usr/lib/systemd/systemVendor definitionsHigher listed directory wins for these paths/etc/systemd/systemAdministrator overrides/run/systemd/systemRuntime overrides/usr/lib/systemd/systemVendor definitionsHigher listed directory wins forthese paths
Administrator configuration overrides runtime and vendor definitions for ordinary same-named unit files.

For your own service, these commands inspect status, control it now, and change its future activation:

bash
systemctl status board-heartbeat.service
sudo systemctl start board-heartbeat.service
sudo systemctl stop board-heartbeat.service
sudo systemctl restart board-heartbeat.service
sudo systemctl enable board-heartbeat.service
systemctl is-enabled board-heartbeat.service
sudo systemctl disable board-heartbeat.service

Enabling a stopped service does not start it unless you add --now. Start and stop change runtime state. Restart stops and starts it again, possibly interrupting work. Enable creates activation links using [Install]. Disable removes those links but does not stop the running service without --now. Dependencies, sockets, timers and manual requests can still start a disabled service.

sudo systemctl mask name.service normally creates an overriding link to /dev/null to block activation. unmask removes that block. Masking may fail if a local file already occupies the destination in /etc. Do not overwrite that file to force masking. Units marked static lack installation instructions and are expected to start another way.

For example, multi-user.target provides non-graphical multi-user operation. graphical.target builds on it, requesting graphical login support if installed. default.target normally aliases the chosen default. In a disposable VM with console access, inspect targets, change the default and isolate multi-user operation:

bash
systemctl get-default
systemctl list-units --type=target
# In a disposable VM with console access:
sudo systemctl set-default multi-user.target
sudo systemctl isolate multi-user.target
# Restore the chosen default if graphical support is installed:
sudo systemctl set-default graphical.target

Here set-default changes future boot selection. Isolate changes the current selection. It stops units outside the new dependency set, except those configured to ignore isolation. Your graphical applications or remote connection may stop. rescue.target starts basic services and a maintenance shell. emergency.target starts a smaller shell without requesting the normal services and mounts. Existing mounts and their read/write state depend on how you entered recovery.

Several targets can be active together. Targets form a dependency graph: links describe which units need others. Historical SysV runlevels were numbered operating modes. Compatibility aliases commonly map 2–4 to multi-user, 5 to graphical and 1 to rescue. These aliases do not reduce the graph to one current runlevel number.

02

Writing a service with a clear process contract

5 min read

For example, a daemon under systemd normally stays in the foreground, without detaching into the background. Systemd supervises it and connects its logs. Adding & makes tracking its lifetime harder without useful independence.

This teaching service prints periodic messages and does not touch hardware. Install it only on lab Linux. The lab asks you to adapt the mechanism and demonstrate it after reboot. The example explains its parts; you must collect your own lab evidence.

1Provide an executable program

Create /usr/local/libexec/board-heartbeat with root ownership and a root-owned parent directory. Set mode 0755, which lets its owner write and everyone read and execute. The script below prints a label every 30 seconds:

The root-owned /usr/local/libexec/board-heartbeat script uses 0755 = -rwxr-xr-x: its owner can read, write and execute it; group and others, including the service running as nobody, can read and execute but cannot write it.

  • octal: 0755
sh
#!/bin/sh
set -eu
label=${HEARTBEAT_LABEL:-board}
while :; do
    printf 'heartbeat: %s\n' "$label"
    sleep 30
done

Here #!/bin/sh selects POSIX /bin/sh, available on the intended target. POSIX specifies portable operating-system interfaces. set -e requests exit for certain command failures; set -u rejects unset variables unless an expansion supplies a default. These options have exceptions explained in the scripting lessons. while : repeats because : always succeeds. printf writes standard output. sleep pauses instead of busy-waiting, which would continuously use a processor.

${...:-...} supplies a default when needed. Quoting "$label" keeps spaces and wildcard characters from becoming extra arguments. The service needs no working directory or files under /home/learner. It can therefore run independently of a login session.

2Separate configuration from the executable

Create the root-owned configuration file /etc/default/board-heartbeat with this label setting:

ini
HEARTBEAT_LABEL=lab-board

An environment file can supply the label as a name/value pair. It is not a shell script. Do not add command substitutions, export commands or shell functions. Environment variables are strings passed to a process. They are unsuitable for secrets needing protection from process inspection or accidental logs. Systemd credentials provide a separate mechanism for that need.

3Describe supervision and installation

Create /etc/systemd/system/board-heartbeat.service with supervision, restart and boot-activation settings:

ini
[Unit]
Description=Lab board heartbeat
After=local-fs.target
StartLimitIntervalSec=60
StartLimitBurst=3

[Service]
Type=simple
User=nobody
EnvironmentFile=/etc/default/board-heartbeat
ExecStart=/usr/local/libexec/board-heartbeat
Restart=on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal
NoNewPrivileges=yes

[Install]
WantedBy=multi-user.target

ExecStart= names the program and arguments without invoking an interactive shell. Systemd parses it itself. It does not expand ~ or interpret | and > as shell pipelines or redirections. Use a script for shell syntax. User=nobody suits this isolated demonstration without private state. In a product, create a dedicated service account so unrelated services do not share one identity.

If this EnvironmentFile= is missing, startup fails. Prefix its path with - only when absence is acceptable. PID 1 reads the file before launching the restricted process. NoNewPrivileges=yes stops that process and descendants from gaining privileges through mechanisms such as set-user-ID executables. These executables can otherwise run with their owner's authority. The setting neither removes all existing permissions nor fully isolates the service.

Restart=on-failure retries qualifying failures such as nonzero exits, but not an intentional systemctl stop. A successful normal exit does not restart this service either. RestartSec= separates attempts. Start-limit settings bound repeated starts, including automatic retries. They limit rapid failure loops without fixing their cause.

Enable uses WantedBy=multi-user.target to create a link in multi-user.target.wants/. Activating the target then requests this service. [Install] describes installation. Its presence alone does not make PID 1 treat it as a runtime dependency.

4Validate, reload and observe

Check the unit, reload manager configuration, enable and start it, then inspect status and this boot's logs:

bash
sudo systemd-analyze verify /etc/systemd/system/board-heartbeat.service
sudo systemctl daemon-reload
sudo systemctl enable --now board-heartbeat.service
systemctl status board-heartbeat.service
sudo journalctl -u board-heartbeat.service -b --no-pager
Writing, enabling and observing a service
 nobody configured, this is not safe!
Nov 30 14:56:34 embeddex systemd[1]: Started board-heartbeat.service - Lab board heartbeat.
Nov 30 14:56:34 embeddex board-heartbeat[268]: heartbeat: lab-board
Nov 30 14:56:34 embeddex systemd[1]: Stopping board-heartbeat.service - Lab board heartbeat...
Nov 30 14:56:34 embeddex systemd[1]: board-heartbeat.service: Deactivated successfully.
Nov 30 14:56:34 embeddex systemd[1]: Stopped board-heartbeat.service - Lab board heartbeat.
Nov 30 14:56:34 embeddex systemd[1]: /etc/systemd/system/board-heartbeat.service:9: Special user
 nobody configured, this is not safe!
Nov 30 14:56:34 embeddex systemd[1]: /etc/systemd/system/board-heartbeat.service:9: Special user
 nobody configured, this is not safe!
Nov 30 14:56:34 embeddex systemd[1]: /etc/systemd/system/board-heartbeat.service:9: Special user
 nobody configured, this is not safe!
Nov 30 14:56:34 embeddex systemd[1]: Started board-heartbeat.service - Lab board heartbeat.
Nov 30 14:56:35 embeddex board-heartbeat[275]: heartbeat: lab-board
Nov 30 14:56:35 embeddex systemd[1]: /etc/systemd/system/board-heartbeat.service:9: Special user
 nobody configured, this is not safe!
Nov 30 14:56:35 embeddex systemd[1]: /etc/systemd/system/board-heartbeat.service:9: Special user
 nobody configured, this is not safe!
Nov 30 14:56:36 embeddex systemd[1]: /etc/systemd/system/board-heartbeat.service:9: Special user
 nobody configured, this is not safe!
Nov 30 14:56:36 embeddex systemd[1]: /etc/systemd/system/board-heartbeat.service:9: Special user
 nobody configured, this is not safe!

learner@embeddex:~/lab$

Verification can catch syntax or reference problems, but cannot prove hardware access or correct application behavior. Daemon-reload rereads units and reruns generators, the programs that create units from other configuration. It does not restart the service. After changing a running program's configuration or executable, use its supported reload method or restart deliberately. System services do not inherit your terminal environment. Check interpreter paths, permissions and configuration.

A service's declared contractboard-heartbeat.serviceExecStartForeground scriptEnvironmentFileExplicit configurationUserRestricted process identityJournalStandard output and errorsWantedByEnable creates target linkboard-heartbeat.serviceExecStartForeground scriptEnvironmentFileExplicit configurationUserRestricted process identityJournalStandard output and errorsWantedByEnable creates target link
A local unit connects a foreground process, configuration, logging and boot activation.

To undo this example, run sudo systemctl disable --now board-heartbeat.service. Remove only its three authored files, then run daemon-reload. Before target experiments, record the original default target so you can restore it separately.

Key takeaways

  • Starting a unit now and enabling its future activation are separate operations.
  • Targets describe groups of units; switching targets can terminate your session.
  • A systemd daemon stays in the foreground; adding & makes its lifetime harder to track.
  • ExecStart is parsed by systemd, so shell operators like | and > are not interpreted; put shell syntax in a script.
Reflect
  1. Explain to a colleague, in two sentences: use systemctl to inspect units, manage services and select targets.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close