Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Part 2 · System administration · Lesson 08 · 50 minutes

Run, write and repair a systemd service

After this lesson you can
  • 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
Lab files of this lesson (16)

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.

What happens at systemctl start
YousystemdServiceJournalsystemctl start kr-hello asks PID 1run the ExecStart commandeach output line is a log entryit logs the start and any failureYousystemdServiceJournal1234
  1. You → systemd: systemctl start kr-hello asks PID 1
  2. systemd → Service: run the ExecStart command
  3. Service → Journal: each output line is a log entry
  4. systemd → Journal: it logs the start and any failure

A unit file has sections. The three that a service needs:

SectionKeyMeaning
[Unit]Description=A line of text for the lists
[Service]ExecStart=The command to run: a full path
[Service]Restart=on-failureStart it again when it dies with an error
[Service]DynamicUser=yesRun it as a temporary user with no rights
[Install]WantedBy=multi-user.targetStart 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.target

After= 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
done

Then 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.target

install -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-reload

The 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-pager
active
● 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 2
The Loaded line of systemctl status
loadedsystemd has read the unit file/etc/systemd/system/kr-hello...the unit filedisableddoes not start at bootpreset: enabledthe distribution defaultloadedsystemd has read the unit file/etc/systemd/system/kr-hello...the unit filedisableddoes not start at bootpreset: enabledthe distribution default

The 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-hello
inactive
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".
disabled

systemctl 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 cat
kr-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
A crash and the restart
YouServicesystemdJournalkill -9 sends SIGKILLthe main process exitslogs code=killed, status=9/KILLRestart=on-failure starts it againhello number 1YouServicesystemdJournal12345
  1. You → Service: kill -9 sends SIGKILL
  2. Service → systemd: the main process exits
  3. systemd → Journal: logs code=killed, status=9/KILL
  4. systemd → Service: Restart=on-failure starts it again
  5. 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.sh

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

The 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-broken
active

reset-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-reload

Your 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 infinity

kr-beacon.service

[Unit]
Description=Beacon service of the lab

[Service]
ExecStart=/usr/local/bin/kr-beacon.sh

[Install]
WantedBy=multi-user.target

Run 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-reload

There 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. Run sudo 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 NAME gives a score and lists what is still open.
  • systemctl mask NAME makes a service impossible to start, by hand or by a dependency. Use it for a service that must never run. systemctl unmask undoes it.
  • The journal can be kept across reboots with Storage=persistent in /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 1 first.
  • Logs and backups belong together: logrotate keeps the logs of /var/log from filling the disk, and lesson 5 of Part 3 shows rsync for backups.