On almost every Linux server, systemd starts the programs that matter, restarts them when they crash, orders them at boot, collects their logs, and runs scheduled jobs. A service is a small text file, a unit, that says what to run, as whom, after what, and what to do when it fails. This lesson writes one unit, follows it from systemctl start to a reboot, and shows the restart loop and the dependency mistake that take services down.
Difficulty: Intermediate · Know this first: Lesson 02, Lesson 07
This bar adds up the seconds the service is not serving across its trip. It is a worked example, not a measurement. The restart and dependency hops are where systemd settings decide minutes of downtime.
Set how quickly the program crashes after starting, the restart delay, and the start limit. systemd counts starts in a 10-second window; past the limit, the unit fails and stays down.
Failed: too many starts in 10 seconds; systemd stops restarting it
Three questions. No score is saved anywhere — this is just you against the material.
systemd grows in four levels: running units, then writing them, then hardening and scheduling, and finally fleet-wide practice.
At the basic level you can control a service and find out why it stopped.
systemctl status|start|stop|restart|enable|disable app.systemctl --failed, systemctl list-units --type=service.journalctl -u app -b, -f to follow.Where it breaks: starting a service by hand and forgetting to enable it, so it is gone after the next reboot.
Try it: Basic
A service runs now but is missing after a reboot. What was skipped?
Now do it: Run systemctl is-enabled on five services you rely on.
At the intermediate level you write correct units.
ExecStart= with full paths, User=, WorkingDirectory=, EnvironmentFile=.Restart=on-failure, RestartSec=, Type=notify or simple.systemctl edit nginx writes a drop-in under nginx.service.d/override.conf.Try it: Intermediate
You need to change one setting in a unit that came with a package. What is the right way?
Now do it: Add a drop-in that sets Restart=on-failure for a service on a test machine and check systemctl cat.
At the advanced level units are safe and scheduled work is visible.
NoNewPrivileges=, ProtectSystem=strict, PrivateTmp=, ReadWritePaths=; score with systemd-analyze security.MemoryMax=, CPUQuota=, TasksMax=.OnCalendar= and Persistent=true instead of cron.Try it: Advanced
Why might you move a nightly cron job to a systemd timer?
Now do it: Convert one cron job to a .timer and .service pair and check systemctl list-timers.
At the master level units are code and failures page someone.
Trade-off: aggressive restarts hide flapping services; conservative ones turn small faults into outages. Choose per service and alert on restarts either way.
Try it: Master
A service restarts 200 times a day without anyone noticing. What would surface it?
Now do it: Check NRestarts for every service on one host: systemctl show -p NRestarts --value app.
A complete unit with sandboxing and a nightly timer. Save the files, then run the commands below.
[Unit] Description=Example app Wants=network-online.target After=network-online.target [Service] Type=simple User=app WorkingDirectory=/var/lib/app ExecStart=/usr/bin/python3 -m http.server 8080 Restart=on-failure RestartSec=5 NoNewPrivileges=yes ProtectSystem=strict ReadWritePaths=/var/lib/app MemoryMax=256M [Install] WantedBy=multi-user.target
# /etc/systemd/system/app-cleanup.service [Service] Type=oneshot ExecStart=/usr/bin/find /var/lib/app/tmp -mtime +7 -delete # /etc/systemd/system/app-cleanup.timer [Timer] OnCalendar=*-*-* 02:00 Persistent=true [Install] WantedBy=timers.target
sudo useradd -r -s /usr/sbin/nologin -d /var/lib/app app; sudo install -d -o app /var/lib/app/tmp sudo systemctl daemon-reload sudo systemctl enable --now app.service app-cleanup.timer systemctl status app; systemctl list-timers app-cleanup.timer systemd-analyze security app.service | tail -1
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A config change turned into a silent outage.
Config is validated before it is written (ExecStartPre= runs the program's check mode), failed units page on-call, and changes roll out one host at a time with a health gate.
Write a unit file, check it, and run it as a service or on a timer; then read its state and logs. Writing and checking unit files needs no root, so those commands run here; starting services needs root, so those are shown. There are 18 commands below, in the order you would use them. Each one shows what it printed when we ran it, so you can compare your screen with it; where the output depends on your machine, the note tells you what to look for.
Every command below works on these files, so run this first, in an empty folder (mkdir -p ~/practice && cd ~/practice). It only creates files there.
cat > lab-web.service <<'EOF' [Unit] Description=Lab web server After=network-online.target Wants=network-online.target [Service] ExecStart=/usr/bin/python3 -m http.server 8088 Restart=on-failure RestartSec=2 DynamicUser=yes MemoryMax=200M CPUQuota=50% [Install] WantedBy=multi-user.target EOF cat > lab-report.timer <<'EOF' [Timer] OnCalendar=Mon..Fri *-*-* 02:00 RandomizedDelaySec=10min Persistent=true [Install] WantedBy=timers.target EOF cat > status.txt <<'EOF' UNIT LOAD ACTIVE SUB DESCRIPTION cron.service loaded active running Regular background program processing daemon lab-web.service loaded failed failed Lab web server nginx.service loaded active running A high performance web server backup.service loaded inactive dead Nightly backup ssh.service loaded active running OpenBSD Secure Shell server worker@1.service loaded failed failed Queue worker 1 EOF
The sections and the lines that matter most: what to run, when to restart, and which target starts it at boot.
$ grep -E "^\[|^(ExecStart|Restart|WantedBy)=" lab-web.service [Unit] [Service] ExecStart=/usr/bin/python3 -m http.server 8088 Restart=on-failure [Install] WantedBy=multi-user.target
Check a unit file for mistakes before installing it.
$ systemd-analyze verify ./lab-web.service && echo "unit file is valid" unit file is valid
Show the unit file systemd is really using, plus any drop-in overrides.
$ systemctl cat ssh.serviceAny property, machine-readable, for scripts.
$ systemctl show nginx -p Restart,MainPID,MemoryCurrent,NRestartsInstall the unit and make systemd re-read its files; forget daemon-reload and it runs the old version.
$ sudo cp lab-web.service /etc/systemd/system/ && sudo systemctl daemon-reloadenable starts it at boot; --now also starts it now.
$ sudo systemctl enable --now lab-webActive state, main PID, memory, and the last log lines.
$ systemctl status lab-web --no-pagerWrite an override (a drop-in) instead of editing the vendor's file, so package upgrades keep your change.
$ sudo systemctl edit lab-webRestart stops and starts; reload asks the program to re-read its configuration without stopping.
$ sudo systemctl restart lab-web; sudo systemctl reload nginxEvery unit in the failed state.
$ systemctl --failed --no-pagerFrom a saved systemctl list-units: the failed units.
$ awk '$3 == "failed" {print $1}' status.txt lab-web.service worker@1.service
Units per state.
$ awk 'NR > 1 {n[$3]++} END {for (s in n) print s, n[s]}' status.txt | sort active 3 failed 2 inactive 1
The last 20 log lines of one unit, this boot only.
$ journalctl -u lab-web -b --no-pager -n 20Clear the failed state after you fix the cause, so the start limit starts counting again.
$ sudo systemctl reset-failed lab-webPersistent=true runs a missed job after the machine was off; a random delay stops every server running it at the same second.
$ grep -E "^(OnCalendar|Persistent|RandomizedDelaySec)" lab-report.timer OnCalendar=Mon..Fri *-*-* 02:00 RandomizedDelaySec=10min Persistent=true
Check what a calendar expression means and when it next fires (from a fixed time, so the output is the same for you).
$ systemd-analyze calendar --base-time="2026-11-03 10:00:00 UTC" "Mon..Fri *-*-* 02:00" | grep -v "From now" Original form: Mon..Fri *-*-* 02:00 Normalized form: Mon..Fri *-*-* 02:00:00 Next elapse: Wed 2026-11-04 02:00:00 UTC
The next three runs of a monthly job.
$ systemd-analyze calendar --iterations=3 --base-time="2026-11-03 10:00:00 UTC" "*-*-01 03:00" | grep -E "elapse" Next elapse: Tue 2026-12-01 03:00:00 UTC
Every timer, when it last ran, and when it runs next.
$ systemctl list-timers --all --no-pagerEach task uses the practice folder. Try it first, then open the solution to compare; there is usually more than one right answer.
Print just the command that lab-web.service runs.
$ grep "^ExecStart=" lab-web.service | cut -d= -f2- /usr/bin/python3 -m http.server 8088
Check when "Sat *-*-* 23:30" next fires after 3 November 2026, 10:00 UTC.
$ systemd-analyze calendar --base-time="2026-11-03 10:00:00 UTC" "Sat *-*-* 23:30" | grep "Next elapse" Next elapse: Sat 2026-11-07 23:30:00 UTC
From status.txt, print the names of failed units without the .service suffix.
$ awk '$3 == "failed" {sub(/\.service$/, "", $1); print $1}' status.txt lab-web worker@1
Print the resource limits set in lab-web.service.
$ grep -E "^(MemoryMax|CPUQuota)=" lab-web.service MemoryMax=200M CPUQuota=50%
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: A Linux VM or a spare machine where you have sudo (a cloud VM, Multipass, or VirtualBox). Some commands change the system; do not run them on a shared server.
Type each one, read what it prints, and compare it with the note above it.
Write a small service unit and start it.
sudo tee /etc/systemd/system/lab-web.service >/dev/null <<'EOF'
[Unit]
Description=Lab web server
Wants=network-online.target
After=network-online.target
[Service]
ExecStart=/usr/bin/python3 -m http.server 8088
Restart=on-failure
RestartSec=2
DynamicUser=yes
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload && sudo systemctl enable --now lab-web
systemctl status lab-web --no-pager | head -5; curl -s -o /dev/null -w "%{http_code}\n" localhost:8088Kill it and watch systemd restart it.
sudo systemctl kill -s KILL lab-web; sleep 3; systemctl show lab-web -p NRestarts,ActiveState
Read only this unit's logs from this boot.
journalctl -u lab-web -b --no-pager | tail -5
A timer that runs a job every minute, then clean everything up.
printf "[Service]\nType=oneshot\nExecStart=/usr/bin/logger lab-tick\n" | sudo tee /etc/systemd/system/lab-tick.service >/dev/null
printf "[Timer]\nOnCalendar=*-*-* *:*:00\nPersistent=true\n[Install]\nWantedBy=timers.target\n" | sudo tee /etc/systemd/system/lab-tick.timer >/dev/null
sudo systemctl daemon-reload && sudo systemctl enable --now lab-tick.timer; systemctl list-timers lab-tick.timer --no-pager
sudo systemctl disable --now lab-web lab-tick.timer; sudo rm /etc/systemd/system/lab-{web,tick}.* ; sudo systemctl daemon-reloadrestart_policy.pyThis program simulates systemd's restart policy and start limit for three kinds of failure, so you can see why a crash loop ends with the unit marked failed. Save it as restart_policy.py, then run it.
# restart_policy.py
def simulate(name, lifetimes, restart_sec=1, burst=5, interval=10):
t, starts, log = 0.0, [], []
for life in lifetimes:
starts = [s for s in starts if s > t - interval] + [t]
if len(starts) > burst:
log.append(f"t={t:5.1f}s start limit hit ({burst} in {interval}s): unit FAILED, no more restarts")
return log
if life is None:
log.append(f"t={t:5.1f}s started, still running")
return log
t += life
log.append(f"t={t:5.1f}s crashed after {life}s, restart in {restart_sec}s")
t += restart_sec
return log
cases = {
"one crash at night": [3600, None],
"flaky, crashes every 30 s": [30, 30, 30, None],
"bad config, exits at once": [0.2] * 10,
}
for name, lifetimes in cases.items():
print(f"== {name}")
for line in simulate(name, lifetimes):
print(" " + line)
Run it, and you should see this output:
$ python3 restart_policy.py == one crash at night t=3600.0s crashed after 3600s, restart in 1s t=3601.0s started, still running == flaky, crashes every 30 s t= 30.0s crashed after 30s, restart in 1s t= 61.0s crashed after 30s, restart in 1s t= 92.0s crashed after 30s, restart in 1s t= 93.0s started, still running == bad config, exits at once t= 0.2s crashed after 0.2s, restart in 1s t= 1.4s crashed after 0.2s, restart in 1s t= 2.6s crashed after 0.2s, restart in 1s t= 3.8s crashed after 0.2s, restart in 1s t= 5.0s crashed after 0.2s, restart in 1s t= 6.0s start limit hit (5 in 10s): unit FAILED, no more restarts
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/systemd-services-units-and-timers && cd ~/labs/systemd-services-units-and-timers) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Running Services with systemd: Units, Restarts, and Timers", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Write a small service unit and start it.'
'Kill it and watch systemd restart it.'
'Read only this unit'\''s logs from this boot.'
'A timer that runs a job every minute, then clean everything up.'
)
step_1() {
sudo tee /etc/systemd/system/lab-web.service >/dev/null <<'EOF'
[Unit]
Description=Lab web server
Wants=network-online.target
After=network-online.target
[Service]
ExecStart=/usr/bin/python3 -m http.server 8088
Restart=on-failure
RestartSec=2
DynamicUser=yes
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload && sudo systemctl enable --now lab-web
systemctl status lab-web --no-pager | head -5; curl -s -o /dev/null -w "%{http_code}\n" localhost:8088
}
step_2() {
sudo systemctl kill -s KILL lab-web; sleep 3; systemctl show lab-web -p NRestarts,ActiveState
}
step_3() {
journalctl -u lab-web -b --no-pager | tail -5
}
step_4() {
printf "[Service]\nType=oneshot\nExecStart=/usr/bin/logger lab-tick\n" | sudo tee /etc/systemd/system/lab-tick.service >/dev/null
printf "[Timer]\nOnCalendar=*-*-* *:*:00\nPersistent=true\n[Install]\nWantedBy=timers.target\n" | sudo tee /etc/systemd/system/lab-tick.timer >/dev/null
sudo systemctl daemon-reload && sudo systemctl enable --now lab-tick.timer; systemctl list-timers lab-tick.timer --no-pager
sudo systemctl disable --now lab-web lab-tick.timer; sudo rm /etc/systemd/system/lab-{web,tick}.* ; sudo systemctl daemon-reload
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
head, tail, curl, kill, rm, Pipes, Redirection, If...Else, Here documents.Run a small web API and its nightly report job on ten Linux servers with systemd.
What must the API wait for at boot? How fast should it restart, and when should it give up? How will you know a unit failed? What should the nightly job do if the server was off at 02:00?
Say ten servers, one API per server, a report that takes 5 minutes, and a target of under 30 seconds downtime per crash.
A Type=notify unit with Wants= and After= for the network and the database, Restart=on-failure and RestartSec=5, ExecStartPre= to validate config, sandboxing and MemoryMax=, a .timer with Persistent=true for the report, units shipped by configuration management, and alerts on failed units and restart counts.
Fast restarts keep a flaky service up and can hide a real bug; a start limit stops a loop and leaves the service down. Validating config in ExecStartPre= adds start time and removes the most common crash loop.