Skip to main content
cd ..

Mastering Systemd: The Linux Service Manager

8 min read
Mastering Systemd: The Linux Service Manager

Understanding Systemd

systemd is the init system used by most modern Linux distributions (Arch, Debian, Ubuntu, Fedora, CentOS). It is responsible for bootstrapping the user space and managing user processes.

While often controversial, its power and ubiquity make it an essential tool for any Linux administrator or DevOps engineer.

The Unit File

At the core of systemd is the unit. Units are defined by configuration files ending in .service, .socket, .target, etc.

Here is a typical service unit file for a custom web server:

[Unit]
Description=My Custom Web Server
After=network.target
[Service]
Type=simple
User=www-data
ExecStart=/usr/bin/python3 -m http.server 8080
Restart=on-failure
[Install]
WantedBy=multi-user.target

Essential Commands

You interact with systemd primarily through the systemctl command.

Managing Services

Terminal window
# Start a service
sudo systemctl start nginx
# Stop a service
sudo systemctl stop nginx
# Restart a service
sudo systemctl restart nginx
# Reload configuration without dropping connections
sudo systemctl reload nginx

Checking Status

The most useful command you’ll use daily:

Terminal window
systemctl status nginx

This gives you:

  1. Loaded: Is the unit file loaded properly?
  2. Active: Is it running, exited, or failed?
  3. Logs: The last few lines of log output.

Enabling for Boot

To make sure a service starts when the server boots up:

Terminal window
sudo systemctl enable nginx

This creates a symlink in /etc/systemd/system/multi-user.target.wants/ pointing to the unit file.

Creating Your Own Service

Let’s say you have a background worker script in python located at /opt/worker/main.py.

  1. Create the unit file at /etc/systemd/system/worker.service:
[Unit]
Description=Python Background Worker
After=network.target
[Service]
User=worker
WorkingDirectory=/opt/worker
ExecStart=/usr/bin/python3 main.py
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
  1. Reload the daemon to read the new file:
Terminal window
sudo systemctl daemon-reload
  1. Start and enable it:
Terminal window
sudo systemctl enable --now worker.service

Troubleshooting

If a service fails to start, check the logs with journalctl:

Terminal window
# View logs for a specific unit
sudo journalctl -u worker.service
# Follow logs in real-time (like tail -f)
sudo journalctl -u worker.service -f
# Check kernel logs (useful for OOM errors)
sudo journalctl -k

Summary

Systemd is complex, but mastering its basics—units, dependencies, and systemctl—is fundamental to managing Linux systems effectively. Whether you’re deploying web servers or building embedded devices, systemd is likely the engine running under the hood.