Service Management with systemd
Objective
Manage system services using systemctl, create custom unit files, and investigate service logs with journalctl.
Tools & Technologies
systemctljournalctlunit files/etc/systemd/system/
Key Commands
systemctl status nginxsystemctl enable --now nginxjournalctl -u nginx -n 50systemctl list-units --failedArchitecture Overview
stateDiagram-v2
[*] --> Inactive: unit file exists
Inactive --> Active: systemctl start
Active --> Inactive: systemctl stop
Active --> Reloading: systemctl reload
Reloading --> Active: reload complete
Active --> Failed: process crashes
Failed --> Active: systemctl restart
Inactive --> Enabled: systemctl enable
Enabled --> Active: boot
Step-by-Step Process
01
Basic Service Control
Start, stop, restart, and check the status of services.
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx # reload config without stopping
sudo systemctl status nginx
sudo systemctl enable nginx # start at boot
sudo systemctl disable nginx
sudo systemctl is-active nginx
02
View Logs with journalctl
journalctl provides structured logs from all systemd services.
journalctl -u nginx # all nginx logs
journalctl -u nginx -n 50 # last 50 lines
journalctl -u nginx -f # follow (tail -f)
journalctl -u nginx --since '1 hour ago'
journalctl -p err -u nginx # errors only
journalctl --disk-usage # log storage size
03
Create a Custom Unit File
Write a systemd service unit file to manage a custom application.
# /etc/systemd/system/myapp.service
[Unit]
Description=My Custom App
After=network.target
[Service]
Type=simple
User=appuser
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/myapp --config /etc/myapp.conf
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
# Load and start:
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
Challenges & Solutions
- Forgetting daemon-reload after editing unit files — systemd uses stale config
- Unit file syntax errors silently prevent service from starting — check with systemctl status
Key Takeaways
- systemctl list-units --failed shows all broken services at a glance
- After=network.target ensures network is up before your service starts