Skip to main content

Managing Linux Services with systemd

Manage Linux services with systemd. Use systemctl, write a hardened unit file for a Node.js app, add overrides, and debug failures with journalctl.

30 Terms

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 status output 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.

flowchart TD A([Kernel starts
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. Use After= together with Wants= or Requires=.

Detailed Step-by-Step Practical Lab

Milestone 1: How to Use the Essential systemctl Commands
Bash
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx # stop, then start (drops connections)
sudo systemctl reload nginx # re-read config without a restart
sudo systemctl reload-or-restart nginx # reload if supported, else restart
sudo systemctl enable nginx
sudo systemctl enable --now nginx # enable at boot and start immediately
sudo systemctl disable --now nginx
# State checks that work in scripts
systemctl status nginx
systemctl is-active nginx # exit code 0 = active
systemctl is-enabled nginx # exit code 0 = enabled
# Tell systemd to re-read unit files after you edit one
sudo systemctl daemon-reload
Common Mistake

Using restart when reload is 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
Bash
systemctl status nginx
TEXT
nginx.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.

Bash
# A failed service shows the result and exit code
systemctl status payment-api
# Active: failed (Result: exit-code) since ...
# Process: 2341 ExecStart=... (code=exited, status=1/FAILURE)
# Everything that has failed
systemctl list-units --type=service --state=failed
systemctl --failed
# What starts at boot
systemctl list-unit-files --type=service --state=enabled
Milestone 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.

Bash
command -v node # note the path, it is used in ExecStart
sudo useradd --system --no-create-home --shell /usr/sbin/nologin payment-svc
sudo 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.in
EOF
sudo chown -R root:payment-svc /opt/payment-api
sudo chmod 600 /etc/payment-api/env

systemd 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
Bash
sudo tee /etc/systemd/system/payment-api.service > /dev/null << 'EOF'
[Unit]
Description=Payment API Service
Documentation=https://internal.devops.in/docs/payment-api
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=60
StartLimitBurst=3
[Service]
Type=simple
User=payment-svc
Group=payment-svc
WorkingDirectory=/opt/payment-api
EnvironmentFile=/etc/payment-api/env
Environment=NODE_ENV=production
Environment=PORT=4000
ExecStart=/usr/bin/node /opt/payment-api/index.js
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
TimeoutStopSec=30
LimitNOFILE=65536
SyslogIdentifier=payment-api
# Sandboxing: give the service only what it needs
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/payment-api
StateDirectory=payment-api
MemoryMax=512M
[Install]
WantedBy=multi-user.target
EOF
# Check syntax before starting
systemd-analyze verify /etc/systemd/system/payment-api.service
sudo systemctl daemon-reload
sudo systemctl enable --now payment-api
systemctl status payment-api
curl -fsS http://127.0.0.1:4000/health

Notes on the choices above:

  1. After= and Wants=network-online.target wait for a configured network before starting. Add After=postgresql.service and Requires=postgresql.service only if the database runs on the same host and your service cannot work without it.
  2. Restart=on-failure restarts after a crash or non-zero exit but not after a clean systemctl stop. StartLimitBurst and StartLimitIntervalSec live in [Unit] and stop a crash loop after three failures in 60 seconds.
  3. StateDirectory=payment-api creates /var/lib/payment-api owned by the service user, which is where a strict sandbox allows writes.
  4. 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:

Bash
sudo kill -9 "$(systemctl show -p MainPID --value payment-api)"
sleep 6
systemctl status payment-api --no-pager
systemctl show payment-api -p NRestarts
Tip

Run systemd-analyze verify every 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.

Bash
# Opens an editor and creates /etc/systemd/system/nginx.service.d/override.conf
sudo systemctl edit nginx
INI
[Service]
LimitNOFILE=65536
Restart=always
RestartSec=3

To create a drop-in non-interactively, for example in a provisioning script:

Bash
sudo mkdir -p /etc/systemd/system/nginx.service.d
sudo tee /etc/systemd/system/nginx.service.d/limits.conf > /dev/null << 'EOF'
[Service]
LimitNOFILE=65536
EOF
sudo systemctl daemon-reload
sudo systemctl restart nginx
# Verify
systemctl show nginx -p LimitNOFILE
systemctl cat nginx # base file plus every drop-in

Some 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=:

INI
[Service]
ExecStart=
ExecStart=/usr/sbin/nginx -g 'daemon off;' -c /etc/nginx/nginx-prod.conf
Milestone 6: How to Query Logs with journalctl
Bash
journalctl -u payment-api # all logs for the unit
journalctl -u payment-api -f # follow live
journalctl -u payment-api -n 50 --no-pager # last 50 lines, no pager
journalctl -xeu payment-api # jump to the end with explanations
# Time ranges
journalctl -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 severe
journalctl -u payment-api -p err
# Boots
journalctl -u payment-api -b # current boot
journalctl -u payment-api -b -1 # previous boot, useful after a crash
# Kernel messages, such as OOM kills
journalctl -k | grep -i 'out of memory'
# Machine-readable output
journalctl -u payment-api -o json --no-pager | jq -r '.MESSAGE' | tail -20
# Journal size and cleanup
journalctl --disk-usage
sudo journalctl --vacuum-time=2weeks
sudo journalctl --vacuum-size=500M

On many servers the journal is kept only in memory and is lost on reboot. To keep it, enable persistent storage:

Bash
sudo mkdir -p /var/log/journal
sudo sed -i 's/^#\?Storage=.*/Storage=persistent/' /etc/systemd/journald.conf
sudo systemctl restart systemd-journald
Milestone 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.

Bash
systemctl get-default
# multi-user.target
systemctl list-units --type=target
sudo systemctl set-default multi-user.target
# How long did boot take, and where did it go?
systemd-analyze
systemd-analyze blame | head -15
systemd-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.

  1. Run every service as its own unprivileged user, never as root.
  2. Set Restart=on-failure with a RestartSec and a start limit so failures recover but do not loop forever.
  3. Add sandboxing options such as NoNewPrivileges, ProtectSystem, and PrivateTmp, then check them with systemd-analyze security.
  4. Keep customisations in /etc/systemd/system/NAME.service.d/, not in package files.
  5. Keep secrets in a root-owned EnvironmentFile= (mode 600) or use LoadCredential=, and out of the unit file.
  6. Make the journal persistent and cap its size.
Security

Anything in Environment= is visible to every local user through systemctl show and systemctl cat. Put secrets in an EnvironmentFile= 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
Tip

The status code in a failed start is a strong hint. 203/EXEC means the binary could not be executed, 217/USER means the account is missing, and 200/CHDIR means WorkingDirectory= does not exist.

Remember

After editing any unit file or drop-in, run sudo systemctl daemon-reload. Without it systemd keeps using the old version, and systemctl status will warn that the unit file changed on disk.

Resources

Explore More in Linux Process and System Management

All 6 Topics

Frequently Asked Questions

Is Managing Linux Services with systemd free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Managing Linux Services with systemd topic cover?

Manage Linux services with systemd. Use systemctl, write a hardened unit file for a Node.js app, add overrides, and debug failures with journalctl.

Found a mistake, an outdated step or a broken link?