systemd Introduction
systemd manages everything that runs on modern Linux: services, mounts, timers, and more. systemctl is how you control it.
Basic Service Management
Enable/Disable on Boot
Check Status
List Services
View Logs
journalctl is Powerful
journalctl replaces reading log files manually. It can filter by time, service, priority, and more.
Create a Service
Create /etc/systemd/system/myapp.service:
[Unit]
Description=My Application
After=network.target
[Service]
Type=simple
User=deploy
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/server
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
Then:
Service Types
| Type | Behavior |
|---|---|
simple | Process in ExecStart is the service |
forking | Process forks, parent exits |
oneshot | Run once, then exit |
notify | Service signals when ready |
Restart Policies
| Restart | When |
|---|---|
no | Never restart |
always | Always restart |
on-failure | Only if failed |
on-abnormal | Abnormal exit |
Reload After Changes
System State
Practical: Node.js Service
# /etc/systemd/system/nodeapp.service
[Unit]
Description=Node.js Application
After=network.target
[Service]
Type=simple
User=deploy
Group=deploy
WorkingDirectory=/var/www/app
Environment=NODE_ENV=production
Environment=PORT=3000
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=nodeapp
[Install]
WantedBy=multi-user.target
What does 'systemctl enable nginx' do?
Quick Reference
| Command | Purpose |
|---|---|
systemctl start svc | Start service |
systemctl stop svc | Stop service |
systemctl restart svc | Restart service |
systemctl status svc | Check status |
systemctl enable svc | Start on boot |
systemctl disable svc | Don't start on boot |
journalctl -u svc | View service logs |
systemctl daemon-reload | Reload unit files |
Key Takeaways
systemctlcontrols servicesstart/stop/restartfor immediate controlenable/disablefor boot behaviorjournalctl -u servicefor logs- Create custom services in
/etc/systemd/system/ - Always
daemon-reloadafter editing unit files
Next: environment variables and shell configuration.