Overview and What You Will Learn
systemd is the init system and service manager on almost every modern Linux distribution. It runs as PID 1, starts services at boot in dependency order, restarts them when they fail, and collects their logs in the journal. You control it with systemctl and read its logs with journalctl.
By the end of this lab you will:
- Start, stop, reload, enable, and inspect services with
systemctl - Read
systemctl statusoutput and find the cause of a failure - Write a unit file for a Node.js application with restart limits and sandboxing
- Customise package-installed units with drop-in overrides instead of editing them
- Query, filter, and follow logs with
journalctl - Explain targets and find slow boot steps with
systemd-analyze
Why This Matters in Production
Before systemd, restarting a crashed service needed tools like monit or supervisor, and logs were scattered across files. systemd handles startup order, restart on failure, resource limits, and logging in one place, which is why the first command in most service incidents is systemctl status SERVICE.
Teams running many services per host, such as those at Grab and Atlassian, rely on correct unit files to get predictable restarts, clean shutdowns, and consistent logs from every service on every server.
Core Principles
systemd reads unit files, builds a dependency graph from the ordering and requirement directives, and starts independent services in parallel. Boot is finished for most servers when multi-user.target is reached.
systemd as PID 1]) --> B[Read unit files
from /etc and /usr/lib] B --> C[Resolve
dependencies] C --> D[Start services
in parallel] D --> E([multi-user.target
reached]) classDef start fill:#475569,color:#ffffff classDef step fill:#326CE5,color:#ffffff classDef done fill:#10B981,color:#ffffff class A start class B,C,D step class E done
Unit files are plain text with three common sections:
| Section | Purpose | Typical keys |
|---|---|---|
[Unit] |
Description and ordering | After=, Wants=, Requires= |
[Service] |
How to run the process | User=, ExecStart=, Restart= |
[Install] |
What enabling does | WantedBy=multi-user.target |
Files are searched in this order, and a file in a higher-priority location wins:
| Location | Used for |
|---|---|
/etc/systemd/system/ |
Your own units and overrides (highest priority) |
/run/systemd/system/ |
Runtime-generated units |
/usr/lib/systemd/system/ |
Units installed by packages |
Remember
After=only controls order, it does not start anything.Wants=starts a dependency but tolerates its failure.Requires=starts it and also stops your service if the dependency fails. UseAfter=together withWants=orRequires=.
Detailed Step-by-Step Practical Lab
Milestone 1: How to Use the Essential systemctl Commands
sudo systemctl start nginxsudo systemctl stop nginxsudo systemctl restart nginx # stop, then start (drops connections)sudo systemctl reload nginx # re-read config without a restartsudo systemctl reload-or-restart nginx # reload if supported, else restart sudo systemctl enable nginxsudo systemctl enable --now nginx # enable at boot and start immediatelysudo systemctl disable --now nginx # State checks that work in scriptssystemctl status nginxsystemctl is-active nginx # exit code 0 = activesystemctl is-enabled nginx # exit code 0 = enabled # Tell systemd to re-read unit files after you edit onesudo systemctl daemon-reloadCommon MistakeUsing
restartwhenreloadis available. A restart stops the process and drops active connections. A reload asks the service to re-read its configuration, which is the zero-downtime option for services such as nginx.
Milestone 2: How to Read systemctl status Output
systemctl status nginxnginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; preset: enabled) Active: active (running) since Mon 2024-01-15 10:00:00 UTC; 2h 15m ago Process: 1098 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS) Main PID: 1100 (nginx) Tasks: 5 (limit: 4915) Memory: 12.4M CGroup: /system.slice/nginx.service |-1100 nginx: master process /usr/sbin/nginx -g daemon off; |-1101 nginx: worker process Jan 15 10:00:00 mumbai-prod-node-1 systemd[1]: Started nginx.Read it from the top. Loaded shows which file was used and whether it starts at boot. Active shows the state and how long it has been in that state. Main PID and CGroup show the processes. The last lines are recent journal entries.
# A failed service shows the result and exit codesystemctl status payment-api# Active: failed (Result: exit-code) since ...# Process: 2341 ExecStart=... (code=exited, status=1/FAILURE) # Everything that has failedsystemctl list-units --type=service --state=failedsystemctl --failed # What starts at bootsystemctl list-unit-files --type=service --state=enabledMilestone 3: How to Create the Service Account and a Test Application
The next milestone runs a small Node.js app, so create the account, directory, config file, and app first.
command -v node # note the path, it is used in ExecStart sudo useradd --system --no-create-home --shell /usr/sbin/nologin payment-svcsudo mkdir -p /opt/payment-api /etc/payment-api sudo tee /opt/payment-api/index.js > /dev/null << 'EOF'const http = require('http');const port = process.env.PORT || 4000;http.createServer((req, res) => { if (req.url === '/health') { res.writeHead(200, {'Content-Type': 'text/plain'}); return res.end('ok\n'); } res.writeHead(404); res.end();}).listen(port, '127.0.0.1', () => console.log(`payment-api listening on ${port}`));EOF sudo tee /etc/payment-api/env > /dev/null << 'EOF'DB_HOST=postgres.mumbai-prod.devops.inEOF sudo chown -R root:payment-svc /opt/payment-apisudo chmod 600 /etc/payment-api/envsystemd reads EnvironmentFile= as root before it drops privileges to User=, so the file can be root-only (mode 600) and the service account never needs to read it.
Milestone 4: How to Write a Unit File for a Node.js Application
sudo tee /etc/systemd/system/payment-api.service > /dev/null << 'EOF'[Unit]Description=Payment API ServiceDocumentation=https://internal.devops.in/docs/payment-apiAfter=network-online.targetWants=network-online.targetStartLimitIntervalSec=60StartLimitBurst=3 [Service]Type=simpleUser=payment-svcGroup=payment-svcWorkingDirectory=/opt/payment-apiEnvironmentFile=/etc/payment-api/envEnvironment=NODE_ENV=productionEnvironment=PORT=4000ExecStart=/usr/bin/node /opt/payment-api/index.jsExecReload=/bin/kill -HUP $MAINPIDRestart=on-failureRestartSec=5TimeoutStopSec=30LimitNOFILE=65536SyslogIdentifier=payment-api # Sandboxing: give the service only what it needsNoNewPrivileges=truePrivateTmp=trueProtectSystem=strictProtectHome=trueReadWritePaths=/var/lib/payment-apiStateDirectory=payment-apiMemoryMax=512M [Install]WantedBy=multi-user.targetEOF # Check syntax before startingsystemd-analyze verify /etc/systemd/system/payment-api.service sudo systemctl daemon-reloadsudo systemctl enable --now payment-apisystemctl status payment-apicurl -fsS http://127.0.0.1:4000/healthNotes on the choices above:
After=andWants=network-online.targetwait for a configured network before starting. AddAfter=postgresql.serviceandRequires=postgresql.serviceonly if the database runs on the same host and your service cannot work without it.Restart=on-failurerestarts after a crash or non-zero exit but not after a cleansystemctl stop.StartLimitBurstandStartLimitIntervalSeclive in[Unit]and stop a crash loop after three failures in 60 seconds.StateDirectory=payment-apicreates/var/lib/payment-apiowned by the service user, which is where a strict sandbox allows writes.- Comments must be on their own line. systemd does not support a comment after a value on the same line.
Test the restart policy by killing the process and watching systemd bring it back:
sudo kill -9 "$(systemctl show -p MainPID --value payment-api)"sleep 6systemctl status payment-api --no-pagersystemctl show payment-api -p NRestartsTipRun
systemd-analyze verifyevery time you write or edit a unit file. It catches unknown keys, misplaced options, and missing executables before you try to start the service.
Milestone 5: How to Override a Package Unit File Without Editing It
Files in /usr/lib/systemd/system/ belong to the package and are overwritten on upgrade. Put your changes in a drop-in file instead.
# Opens an editor and creates /etc/systemd/system/nginx.service.d/override.confsudo systemctl edit nginx[Service]LimitNOFILE=65536Restart=alwaysRestartSec=3To create a drop-in non-interactively, for example in a provisioning script:
sudo mkdir -p /etc/systemd/system/nginx.service.dsudo tee /etc/systemd/system/nginx.service.d/limits.conf > /dev/null << 'EOF'[Service]LimitNOFILE=65536EOF sudo systemctl daemon-reloadsudo systemctl restart nginx # Verifysystemctl show nginx -p LimitNOFILEsystemctl cat nginx # base file plus every drop-inSome keys, such as ExecStart=, are lists. To replace one in a drop-in you must first clear it with an empty assignment, otherwise systemd rejects a second ExecStart=:
[Service]ExecStart=ExecStart=/usr/sbin/nginx -g 'daemon off;' -c /etc/nginx/nginx-prod.confMilestone 6: How to Query Logs with journalctl
journalctl -u payment-api # all logs for the unitjournalctl -u payment-api -f # follow livejournalctl -u payment-api -n 50 --no-pager # last 50 lines, no pagerjournalctl -xeu payment-api # jump to the end with explanations # Time rangesjournalctl -u payment-api --since "1 hour ago"journalctl -u payment-api --since "2024-01-15 10:00" --until "2024-01-15 11:00" # Priority: err and more severejournalctl -u payment-api -p err # Bootsjournalctl -u payment-api -b # current bootjournalctl -u payment-api -b -1 # previous boot, useful after a crash # Kernel messages, such as OOM killsjournalctl -k | grep -i 'out of memory' # Machine-readable outputjournalctl -u payment-api -o json --no-pager | jq -r '.MESSAGE' | tail -20 # Journal size and cleanupjournalctl --disk-usagesudo journalctl --vacuum-time=2weekssudo journalctl --vacuum-size=500MOn many servers the journal is kept only in memory and is lost on reboot. To keep it, enable persistent storage:
sudo mkdir -p /var/log/journalsudo sed -i 's/^#\?Storage=.*/Storage=persistent/' /etc/systemd/journald.confsudo systemctl restart systemd-journaldMilestone 7: How to Understand Targets and Analyse Boot Time
A target is a named group of units that represents a system state. It replaces the old runlevels.
systemctl get-default# multi-user.target systemctl list-units --type=targetsudo systemctl set-default multi-user.target # How long did boot take, and where did it go?systemd-analyzesystemd-analyze blame | head -15systemd-analyze critical-chain # Review how well a service is sandboxed (lower exposure is better)systemd-analyze security payment-api| Target | Meaning |
|---|---|
multi-user.target |
Normal server mode, no GUI |
graphical.target |
Desktop mode with a display manager |
rescue.target |
Single-user recovery shell |
emergency.target |
Minimal shell with the root filesystem read-only |
Production Best Practices & Common Pitfalls
Treat unit files as code: keep them in version control, deploy them with your configuration tool, and verify them before reloading.
- Run every service as its own unprivileged user, never as root.
- Set
Restart=on-failurewith aRestartSecand a start limit so failures recover but do not loop forever. - Add sandboxing options such as
NoNewPrivileges,ProtectSystem, andPrivateTmp, then check them withsystemd-analyze security. - Keep customisations in
/etc/systemd/system/NAME.service.d/, not in package files. - Keep secrets in a root-owned
EnvironmentFile=(mode 600) or useLoadCredential=, and out of the unit file. - Make the journal persistent and cap its size.
SecurityAnything in
Environment=is visible to every local user throughsystemctl showandsystemctl cat. Put secrets in anEnvironmentFile=with mode 600 owned by root, or use systemd credentials. Remember that a process environment can still be read by that service's user and by root.
| Scenario | Wrong | Correct |
|---|---|---|
| Changing a package unit | Edit /usr/lib/systemd/system/ |
Use a drop-in in /etc/systemd/system/NAME.service.d/ |
| Secrets for a service | Environment=DB_PASS=... in the unit |
Root-only EnvironmentFile= |
| Edited a unit file | Restart only | daemon-reload, then restart |
| Crash loop limits | Put StartLimit* in [Service] |
Put them in [Unit] as StartLimitIntervalSec= and StartLimitBurst= |
| Failing service | Reboot the server | systemctl status then journalctl -xeu |
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| Start | sudo systemctl start NAME |
| Enable and start | sudo systemctl enable --now NAME |
| Status | systemctl status NAME |
| Follow logs | journalctl -u NAME -f |
| Errors only | journalctl -u NAME -p err |
| After editing a unit | sudo systemctl daemon-reload |
| Effective unit file | systemctl cat NAME |
| List failures | systemctl --failed |
| Validate a unit | systemd-analyze verify /etc/systemd/system/NAME.service |
| Slow boot steps | systemd-analyze blame |
| Symptom | First command | What to look for |
|---|---|---|
| Service will not start | journalctl -xeu NAME |
Exit code, missing file, permission denied |
| Change has no effect | systemctl cat NAME |
Old value, or an override taking priority |
| "start request repeated too quickly" | systemctl show NAME -p NRestarts |
Start limit reached, fix the cause then systemctl reset-failed NAME |
| Status 203/EXEC | ls -l on the ExecStart path |
Wrong path or missing execute bit |
| Status 217/USER | getent passwd USER |
User= account does not exist |
| Logs gone after reboot | journalctl --list-boots |
Journal not persistent |
TipThe status code in a failed start is a strong hint.
203/EXECmeans the binary could not be executed,217/USERmeans the account is missing, and200/CHDIRmeansWorkingDirectory=does not exist.
RememberAfter editing any unit file or drop-in, run
sudo systemctl daemon-reload. Without it systemd keeps using the old version, andsystemctl statuswill warn that the unit file changed on disk.