Part 2 · System administration · Lesson 08 · 50 minutes
Run, write and repair a systemd service
- List services and start, stop, restart, enable and disable one
- Read a unit file and write a small one of your own
- Find why a service fails with systemctl status and journalctl
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
The team has a small program that must run all the time on the server, and it must start again after a reboot or a crash. Today somebody starts it by hand in a terminal, and it dies when the terminal closes. Your lead asks you to turn it into a service. The same day, another service fails after a change, and the person on call needs to know why. You learn both with a lab service that prints a line every five seconds.
Recall
What does kill -9 do, and why is "kill PID" the better first try?
SIGKILL ends the process at once, and the process cannot clean up. SIGTERM (the default) asks it to finish, so it can close its files. Use -9 last.
You have a sudo rule "kr_ana ALL=(root) NOPASSWD: /usr/bin/systemctl --no-pager status cron". May kr_ana run "sudo systemctl restart cron"?
No. A rule with arguments allows exactly those arguments. restart cron is a different command.
The idea
systemd is the first process (PID 1) of most Linux systems. It starts the other processes and keeps them running. A unit is one thing that systemd manages, described in a text file. A service is a unit of the type .service: a program that systemd starts, watches and restarts. You control units with systemctl, and you read their logs with journalctl. The journal is the log database of systemd.
- You → systemd: systemctl start kr-hello asks PID 1
- systemd → Service: run the ExecStart command
- Service → Journal: each output line is a log entry
- systemd → Journal: it logs the start and any failure
A unit file has sections. The three that a service needs:
| Section | Key | Meaning |
|---|---|---|
[Unit] | Description= | A line of text for the lists |
[Service] | ExecStart= | The command to run: a full path |
[Service] | Restart=on-failure | Start it again when it dies with an error |
[Service] | DynamicUser=yes | Run it as a temporary user with no rights |
[Install] | WantedBy=multi-user.target | Start it at boot (when you enable it) |
Unit files of the system are in /usr/lib/systemd/system/. Your own files go in /etc/systemd/system/, and they win. After you add or change one, run sudo systemctl daemon-reload, so that systemd reads it again.
Worked example
The output comes from a test virtual machine; yours differs a little. cron is installed on most systems. If your system has no cron, use another service from the list.
1. List and read a service
systemctl list-units --type=service lists the loaded services. --state=running keeps those that run, --no-pager prints without a viewer, and --no-legend removes the header and the footer. systemctl status NAME shows one service: Loaded names the unit file and whether it starts at boot, and Active shows its state.
systemctl list-units --type=service --state=running --no-pager --no-legend | head -n 3
systemctl status cron --no-pager | head -n 5 atd.service loaded active running Deferred execution scheduler
cron.service loaded active running Regular background program processing daemon
dbus.service loaded active running D-Bus System Message Bus
● cron.service - Regular background program processing daemon
Loaded: loaded (/usr/lib/systemd/system/cron.service; enabled; preset: enabled)
Active: active (running) since Sat 2026-11-21 19:32:44 UTC; 14min ago
Docs: man:cron(8)
Main PID: 395 (cron)systemctl cat NAME prints the unit file. Read this one from top to bottom:
systemctl cat cron --no-pager | head -n 16# /usr/lib/systemd/system/cron.service
[Unit]
Description=Regular background program processing daemon
Documentation=man:cron(8)
After=remote-fs.target nss-user-lookup.target
[Service]
EnvironmentFile=-/etc/default/cron
ExecStart=/usr/sbin/cron -f -P $EXTRA_OPTS
IgnoreSIGPIPE=false
KillMode=process
Restart=on-failure
SyslogFacility=cron
[Install]
WantedBy=multi-user.targetAfter= orders the start after other units, ExecStart is the command (-f keeps it in the foreground, which systemd needs), and Restart=on-failure is the restart rule. WantedBy=multi-user.target in [Install] is what enable uses to start the service at boot.
2. Write your own service
First the program: a script that prints one line every five seconds. while true; do ... done repeats the lines between do and done for ever, n=$((n + 1)) adds one to the number n, and sleep 5 waits five seconds. Lesson 11 explains these forms. Save it as kr-hello.sh in your lab folder.
kr-hello.sh
#!/bin/bash
# kr-hello.sh - prints one line every 5 seconds
n=0
while true; do
n=$((n + 1))
echo "hello number $n"
sleep 5
doneThen the unit file kr-hello.service:
kr-hello.service
[Unit]
Description=KaliRange hello lab service
[Service]
ExecStart=/usr/local/bin/kr-hello.sh
DynamicUser=yes
Restart=on-failure
[Install]
WantedBy=multi-user.targetinstall -m 755 copies a file and sets its mode in one step. Install both files, and make systemd read them.
cd ~/krlab/linux-admin
sudo install -m 755 kr-hello.sh /usr/local/bin/kr-hello.sh
sudo install -m 644 kr-hello.service /etc/systemd/system/kr-hello.service
sudo systemctl daemon-reloadThe commands print nothing when they work.
3. Start it and read its state and log
start runs the service now. is-active prints one word for the state. journalctl -u NAME (unit) shows the log of one service, -n 4 the last four lines. A user outside the groups adm and systemd-journal sees no log lines (in status too), so use sudo for journalctl. The three last lines below come from it.
sudo systemctl start kr-hello
sleep 7
systemctl is-active kr-hello
systemctl status kr-hello --no-pager
sudo journalctl -u kr-hello -n 4 --no-pageractive
● kr-hello.service - KaliRange hello lab service
Loaded: loaded (/etc/systemd/system/kr-hello.service; disabled; preset: enabled)
Active: active (running) since Sat 2026-11-21 19:47:20 UTC; 7s ago
Main PID: 5190 (kr-hello.sh)
Tasks: 2 (limit: 4493)
Memory: 676.0K (peak: 1.0M)
CPU: 13ms
CGroup: /system.slice/kr-hello.service
├─5190 /bin/bash /usr/local/bin/kr-hello.sh
└─5193 sleep 5
Nov 21 19:47:20 krbox systemd[1]: Started kr-hello.service - KaliRange hello lab service.
Nov 21 19:47:20 krbox kr-hello.sh[5190]: hello number 1
Nov 21 19:47:25 krbox kr-hello.sh[5190]: hello number 2The service runs, but disabled means that it will not start at boot. The CGroup lines list every process of the service: systemd tracks them all, so stop can end them all.
4. Stop, restart, enable and disable
stop ends the service, and restart stops it and starts it again. enable makes the link that starts it at boot, and disable removes the link. enable --now does enable and start together. is-enabled shows whether the link exists. A service can be running and disabled, or stopped and enabled: they are two facts.
sudo systemctl stop kr-hello
systemctl is-active kr-hello
sudo systemctl restart kr-hello
systemctl is-active kr-hello
sudo systemctl enable kr-hello
systemctl is-enabled kr-hello
sudo systemctl disable kr-hello
systemctl is-enabled kr-helloinactive
active
Created symlink /etc/systemd/system/multi-user.target.wants/kr-hello.service → /etc/systemd/system/kr-hello.service.
enabled
Removed "/etc/systemd/system/multi-user.target.wants/kr-hello.service".
disabledsystemctl reload NAME asks a service to read its settings again without a stop, but only a service that supports it. cron does not: systemd answers "Job type reload is not applicable".
5. Watch a crash and the restart
systemctl show -p MainPID --value NAME prints only the PID of the main process. End it with kill -9, and wait a moment. Restart=on-failure starts the service again, and the journal tells the story. -o cat prints only the message of each entry.
sudo kill -9 $(systemctl show -p MainPID --value kr-hello)
sleep 4
sudo journalctl -u kr-hello -n 5 --no-pager -o catkr-hello.service: Main process exited, code=killed, status=9/KILL
kr-hello.service: Failed with result 'signal'.
kr-hello.service: Scheduled restart job, restart counter is at 1.
Started kr-hello.service - KaliRange hello lab service.
hello number 1- You → Service: kill -9 sends SIGKILL
- Service → systemd: the main process exits
- systemd → Journal: logs code=killed, status=9/KILL
- systemd → Service: Restart=on-failure starts it again
- Service → Journal: hello number 1
6. Diagnose a service that fails
Save this unit file as kr-broken.service. It has a typo in the path of the program: kr-helo.sh instead of kr-hello.sh. Start it, and then look in the order that you always use: the list of failed units, status, and the journal.
kr-broken.service
[Unit]
Description=A service with a wrong path
[Service]
ExecStart=/usr/local/bin/kr-helo.shInstall it, start it, and look:
sudo install -m 644 kr-broken.service /etc/systemd/system/kr-broken.service
sudo systemctl daemon-reload
sudo systemctl start kr-broken
systemctl --failed --no-pager --no-legend
systemctl status kr-broken --no-pager
sudo journalctl -u kr-broken --no-pager -n 3
systemd-analyze verify /etc/systemd/system/kr-broken.service● kr-broken.service loaded failed failed A service with a wrong path
× kr-broken.service - A service with a wrong path
Loaded: loaded (/etc/systemd/system/kr-broken.service; static)
Active: failed (Result: exit-code) since Sat 2026-11-21 19:48:02 UTC; 23ms ago
Duration: 1ms
Process: 5423 ExecStart=/usr/local/bin/kr-helo.sh (code=exited, status=203/EXEC)
Main PID: 5423 (code=exited, status=203/EXEC)
CPU: 1ms
Nov 21 19:48:02 krbox systemd[1]: Started kr-broken.service - A service with a wrong path.
Nov 21 19:48:02 krbox systemd[1]: kr-broken.service: Main process exited, code=exited, status=203/EXEC
Nov 21 19:48:02 krbox systemd[1]: kr-broken.service: Failed with result 'exit-code'.
kr-broken.service: Command /usr/local/bin/kr-helo.sh is not executable: No such file or directoryThe start command printed no error: systemd queued the job and the service failed afterwards. Only status and the journal tell you. The code 203/EXEC means that systemd could not run the ExecStart program at all: the path is wrong, or the file has no execute bit. A code from the program itself would show as status=1/FAILURE or similar, and the program's own messages would be in the journal. systemd-analyze verify FILE reads a unit file and names the problem before you start it. sed 's/OLD/NEW/' replaces the first OLD in each line by NEW, and -i changes the file in place. Fix the path and start again:
sudo sed -i 's/kr-helo/kr-hello/' /etc/systemd/system/kr-broken.service
sudo systemctl daemon-reload
sudo systemctl reset-failed kr-broken
sudo systemctl start kr-broken
systemctl is-active kr-brokenactivereset-failed clears the failed mark. Clean up the lab services:
sudo systemctl disable --now kr-hello
sudo systemctl stop kr-broken
sudo rm /etc/systemd/system/kr-hello.service /etc/systemd/system/kr-broken.service /usr/local/bin/kr-hello.sh
sudo systemctl daemon-reloadYour turn
A colleague wrote a service kr-beacon. It does not start. Save the script as kr-beacon.sh and the unit as kr-beacon.service in your lab folder. The script prints one line and then waits for ever.
kr-beacon.sh
#!/bin/bash
echo "beacon: up"
exec sleep infinitykr-beacon.service
[Unit]
Description=Beacon service of the lab
[Service]
ExecStart=/usr/local/bin/kr-beacon.sh
[Install]
WantedBy=multi-user.targetRun this block once to install the files. It is not the task.
cd ~/krlab/linux-admin
sudo install -m 644 kr-beacon.sh /usr/local/bin/kr-beacon.sh
sudo install -m 644 kr-beacon.service /etc/systemd/system/kr-beacon.service
sudo systemctl daemon-reloadThere are no steps here. Start the service, find out why it fails, repair it, make it start at boot and start it. Answer from your own system.
Last, stop and disable the service, and remove its two files.
Check yourself
systemctl start prints nothing, but the service is not running. Where do you look?
start only queues the job and reports an error only when it cannot even do that. Run systemctl status NAME for the state and the exit code, and journalctl -u NAME for the messages of the service and of systemd.
You change a unit file and restart the service, but the old behaviour stays. What did you forget?
sudo systemctl daemon-reload. systemd keeps the unit files in memory, and it reads them again only after that command (it also warns you).
A service is "enabled" and "inactive". What will happen at the next boot?
It will start, because enabled means "start at boot". It is stopped only for now. "Enabled" says what happens at boot, and "active" says what is true now.
Why use DynamicUser=yes, or a user of its own, and not root, for a service?
If the program has a flaw, an attacker gets only the rights of that user. A service as root gives the attacker the whole machine.
Field notes
- Never edit a file in
/usr/lib/systemd/system/: the next update of the package replaces it. Runsudo systemctl edit NAME, which writes a drop-in file in/etc/systemd/system/NAME.service.d/that changes only what you name. - Use the hardening keys of systemd for every service of your own:
NoNewPrivileges=yes,ProtectSystem=strict,ProtectHome=yes,PrivateTmp=yes.systemd-analyze security NAMEgives a score and lists what is still open. systemctl mask NAMEmakes a service impossible to start, by hand or by a dependency. Use it for a service that must never run.systemctl unmaskundoes it.- The journal can be kept across reboots with
Storage=persistentin/etc/systemd/journald.conf. Without it, the log of a crash is gone after the reboot that you needed to fix the crash. - On a system without systemd (an old image, or a container), the commands of this lesson do not work. Read
ps -p 1first. - Logs and backups belong together:
logrotatekeeps the logs of/var/logfrom filling the disk, and lesson 5 of Part 3 showsrsyncfor backups.