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 ServerAfter=network.target
[Service]Type=simpleUser=www-dataExecStart=/usr/bin/python3 -m http.server 8080Restart=on-failure
[Install]WantedBy=multi-user.targetEssential Commands
You interact with systemd primarily through the systemctl command.
Managing Services
# Start a servicesudo systemctl start nginx
# Stop a servicesudo systemctl stop nginx
# Restart a servicesudo systemctl restart nginx
# Reload configuration without dropping connectionssudo systemctl reload nginxChecking Status
The most useful command you’ll use daily:
systemctl status nginxThis gives you:
- Loaded: Is the unit file loaded properly?
- Active: Is it running, exited, or failed?
- Logs: The last few lines of log output.
Enabling for Boot
To make sure a service starts when the server boots up:
sudo systemctl enable nginxThis 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.
- Create the unit file at
/etc/systemd/system/worker.service:
[Unit]Description=Python Background WorkerAfter=network.target
[Service]User=workerWorkingDirectory=/opt/workerExecStart=/usr/bin/python3 main.pyRestart=alwaysRestartSec=3
[Install]WantedBy=multi-user.target- Reload the daemon to read the new file:
sudo systemctl daemon-reload- Start and enable it:
sudo systemctl enable --now worker.serviceTroubleshooting
If a service fails to start, check the logs with journalctl:
# View logs for a specific unitsudo 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 -kSummary
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.