Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

LX
Linux
0/11 completed
Beginner
The Linux file systemUsers, groups and permissionsPackage managers
Intermediate
Processes and signalsDisks, storage and archivesNetworking commandsSSH and remote access
Advanced
systemd and servicesLogs and troubleshooting
Pro
Securing a serverPerformance and resource limits
Tracks / Linux / Advanced

systemd and services

A web app on a server must start when the machine boots, restart if it crashes, run as a safe user, and write its logs somewhere you can find them. On almost every modern Linux system (Ubuntu, Debian, RHEL, Fedora, Arch) that's the job of systemd, the first process the kernel starts (PID 1). You control it with systemctl.

Units

systemd manages units. The ones you'll use most:

Unit type What it is Example
.service A program to run and supervise nginx.service, ssh.service
.timer A schedule that starts a service logrotate.timer
.socket A port or socket that starts a service on demand ssh.socket
.target A group of units, like a "run level" multi-user.target
.mount A mounted file system mnt-data.mount
bash
systemctl list-units --type=service --state=running --no-pager --no-legend | awk '{ print $1 }'
Output
cron.service
dbus.service
systemd-journald.service

Controlling services

bash
sudo systemctl start nginx
systemctl is-active nginx
sudo systemctl stop nginx
systemctl is-active nginx
sudo systemctl restart nginx
sudo systemctl reload nginx
systemctl is-active nginx
Output
active
inactive
active
Command Does
systemctl start name / stop name Start / stop now
systemctl restart name Stop then start (brief downtime)
systemctl reload name Re-read the config without stopping (if the program supports it; nginx does)
systemctl enable name / disable name Start / don't start automatically at boot
systemctl enable --now name Enable and start in one go
systemctl status name State, recent log lines, main PID, memory
systemctl is-active name / is-enabled name One-word answers, handy in scripts
systemctl list-units --failed Everything that's broken

Start/stop and enable/disable are separate: a running service isn't necessarily enabled for the next boot, and vice versa. Forgetting enable is the classic "it all stopped after the reboot" mistake.

bash
systemctl is-enabled nginx
sudo systemctl enable nginx 2>&1 | grep -o "Created symlink.*" | cut -c1-60
systemctl is-enabled nginx
Output
disabled
Created symlink /etc/systemd/system/multi-user.target.wants/
enabled

Reading status

bash
systemctl status nginx --no-pager --lines=0 | head -8
Output
● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: enabled)
     Active: active (running) since Sun 2026-11-22 10:48:46 UTC; 414ms ago
       Docs: man:nginx(8)
   Main PID: 181 (nginx)
      Tasks: 11 (limit: 9396)
     Memory: 6.7M (peak: 13.6M)
        CPU: 24ms

The important lines: Loaded (where the unit file is, enabled or not), Active (running, since when), Main PID, and memory and CPU use. Below them come the processes in the service's CGroup (nginx's master and workers) and the latest log lines (left out here with --lines=0 and head).

Writing your own service

Say you have a small Python web app in /opt/shop. Let's make systemd run it properly. First, the app:

bash
useradd --system --no-create-home --shell /usr/sbin/nologin shop
mkdir -p /opt/shop
cat > /opt/shop/app.py <<'EOF'
import http.server, os, signal, sys

port = int(os.environ.get("PORT", "8000"))

class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/crash":
            print("crashing on purpose!", flush=True)
            os._exit(1)
        body = f"hello from shop, running as uid {os.getuid()}\n".encode()
        self.send_response(200)
        self.end_headers()
        self.wfile.write(body)

def stop(*_):
    print("got SIGTERM, shutting down cleanly", flush=True)
    sys.exit(0)

signal.signal(signal.SIGTERM, stop)
print(f"shop listening on port {port}", flush=True)
http.server.HTTPServer(("127.0.0.1", port), Handler).serve_forever()
EOF
echo "app installed"
Output
app installed

Now the unit file. Your own units go in /etc/systemd/system/:

/etc/systemd/system/shop.service
[Unit]
Description=Shop web app
After=network.target

[Service]
User=shop
Group=shop
WorkingDirectory=/opt/shop
Environment=PORT=8000
ExecStart=/usr/bin/python3 /opt/shop/app.py
Restart=on-failure
RestartSec=2

[Install]
WantedBy=multi-user.target
Line Meaning
After=network.target Start after networking is up
User=, Group= Run as the unprivileged shop account, never root
Environment= Environment variables (or EnvironmentFile=/etc/shop.env for many, including secrets with 600 permissions)
ExecStart= The command, with a full path
Restart=on-failure Restart if it exits with an error or crashes (always restarts even after a clean exit)
WantedBy=multi-user.target What enable hooks it into: the normal boot

Tell systemd about the new file, then enable and start it:

bash
sudo systemctl daemon-reload
sudo systemctl enable --now shop 2>/dev/null
sleep 1
systemctl is-active shop
curl -s http://127.0.0.1:8000/
Output
active
hello from shop, running as uid 999

daemon-reload is needed every time you create or edit a unit file. Forgetting it is the most common reason "my change didn't do anything".

Automatic restarts

Let's crash the app and watch systemd bring it back:

bash
systemctl show shop -p MainPID -p NRestarts | sed 's/MainPID=[0-9]*/MainPID=(old)/'
curl -s http://127.0.0.1:8000/crash
sleep 3
systemctl is-active shop
systemctl show shop -p NRestarts
curl -s http://127.0.0.1:8000/
Output
MainPID=(old)
NRestarts=0
active
NRestarts=1
hello from shop, running as uid 999

That's the main reason to run apps under systemd instead of with nohup or in a tmux session: crashes are survived, and so are reboots.

Stopping cleanly

systemctl stop sends SIGTERM, waits up to 90 seconds (TimeoutStopSec=), then sends SIGKILL. Apps should catch SIGTERM and finish their work, as this one does:

bash
sudo systemctl stop shop
journalctl -u shop --no-pager -o cat | tail -4
Output
got SIGTERM, shutting down cleanly
Stopping shop.service - Shop web app...
shop.service: Deactivated successfully.
Stopped shop.service - Shop web app.

Overrides: changing a unit without editing it

Never edit the unit files installed by packages in /usr/lib/systemd/system/: the next upgrade overwrites them. Add a drop-in override instead. sudo systemctl edit nginx opens an editor for one; in a script, create the file directly:

bash
mkdir -p /etc/systemd/system/shop.service.d
cat > /etc/systemd/system/shop.service.d/override.conf <<'EOF'
[Service]
Environment=PORT=9000
EOF
systemctl daemon-reload
systemctl start shop
sleep 1
curl -s http://127.0.0.1:9000/
systemctl cat shop --no-pager | grep -E "^# |PORT"
Output
hello from shop, running as uid 999
# /etc/systemd/system/shop.service
Environment=PORT=8000
# /etc/systemd/system/shop.service.d/override.conf
Environment=PORT=9000

systemctl cat shows the unit plus all its drop-ins, so you can see the final settings.

Sandboxing a service

systemd can lock a service down far beyond "don't run as root". A few lines make a break-in much less damaging:

bash
echo "before: $(systemd-analyze security shop --no-pager 2>/dev/null | tail -1)"
cat > /etc/systemd/system/shop.service.d/hardening.conf <<'EOF'
[Service]
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
ReadWritePaths=/var/lib/shop
StateDirectory=shop
MemoryMax=200M
EOF
systemctl daemon-reload && systemctl restart shop && sleep 1
curl -s http://127.0.0.1:9000/
echo "after:  $(systemd-analyze security shop --no-pager 2>/dev/null | tail -1)"
Output
before: → Overall exposure level for shop.service: 9.2 UNSAFE :-{
hello from shop, running as uid 999
after:  → Overall exposure level for shop.service: 8.3 EXPOSED :-(
  • ProtectSystem=strict makes the whole file system read-only for the service, except ReadWritePaths.
  • ProtectHome=yes hides /home and /root.
  • PrivateTmp=yes gives it its own empty /tmp.
  • MemoryMax=200M kills it (and lets Restart= bring it back) if it leaks memory.
  • systemd-analyze security name scores a service's exposure from 0 (locked down) to 10 and lists every option you could still add, such as PrivateDevices=, ProtectKernelTunables=, RestrictAddressFamilies= and SystemCallFilter=. Each one you add lowers the score; most web apps can reach the 2–4 range.

Timers: systemd's cron

A timer starts a service on a schedule. Two files: a .service that does the work once, and a .timer that says when:

/etc/systemd/system/cleanup.service
[Unit]
Description=Delete old upload files

[Service]
Type=oneshot
ExecStart=/usr/bin/find /var/lib/shop -name "*.tmp" -mmin +60 -delete
/etc/systemd/system/cleanup.timer
[Unit]
Description=Run cleanup every 15 minutes

[Timer]
OnCalendar=*:0/15
Persistent=true

[Install]
WantedBy=timers.target
bash
sudo systemctl daemon-reload
sudo systemctl enable --now cleanup.timer 2>/dev/null
systemctl is-enabled cleanup.timer
systemctl is-active cleanup.timer
systemd-analyze calendar "Mon..Fri 09:00" --iterations=2 | grep -E "Normalized|Next"| sed -E 's/elapse: .*/elapse: (the next weekday at 09:00)/'
Output
enabled
active
Normalized form: Mon..Fri *-*-* 09:00:00
    Next elapse: (the next weekday at 09:00)
OnCalendar= Means
hourly, daily, weekly Shortcuts
*-*-* 02:30:00 Every day at 02:30
Mon..Fri 09:00 Weekdays at 09:00
*:0/15 Every 15 minutes

Compared with cron, timers log every run in the journal, can run a missed job after the machine was off (Persistent=true), can't overlap themselves, and get all the service options above. Test any schedule with systemd-analyze calendar "…", and see every timer with its next run time in systemctl list-timers.

Boot and targets

bash
systemctl get-default
systemd-analyze blame --no-pager 2>/dev/null | head -3 | awk '{ print $2 }'
Output
graphical.target
systemd-journald.service
systemd-journal-flush.service
dev-hugepages.mount

multi-user.target is the normal server boot (everything except a desktop); graphical.target adds a desktop on top. Ubuntu points the default at graphical.target even on servers, which is harmless: without a desktop installed, it boots the same units as multi-user.target. systemd-analyze blame shows which units slowed the boot down; systemd-analyze critical-chain shows the chain that took the longest.

Practice

  1. Check which services are enabled at boot: systemctl list-unit-files --type=service --state=enabled.
  2. Write a unit for any small program (even python3 -m http.server 8080), running as a non-root user with Restart=on-failure. Kill its process with kill -9 and check that it comes back.
  3. Change one setting of it with a drop-in instead of editing the unit file.
  4. Turn a cron job of yours into a .service + .timer pair.
✎ Check your understanding

1.You start a service with systemctl start app. After a reboot it isn't running. Why?

2.You edited /etc/systemd/system/app.service. What must you run before restarting?

3.How should you change a setting of a unit installed by a package?

4.What does Restart=on-failure do?

← SSH and remote access