What Is systemd?
systemd is the init system and service manager used by most modern Linux distributions. It manages service startup, dependencies, and lifecycle.
Basic Service Commands
# Start a service
sudo systemctl start nginx
# Stop a service
sudo systemctl stop nginx
# Restart a service
sudo systemctl restart nginx
# Reload configuration without restart
sudo systemctl reload nginx
# Check status
systemctl status nginxEnable and Disable Services
# Start automatically on boot
sudo systemctl enable nginx
# Enable and start immediately
sudo systemctl enable --now nginx
# Disable auto-start
sudo systemctl disable nginx
# Check if enabled
systemctl is-enabled nginxViewing Service Information
# List all running services
systemctl list-units --type=service --state=running
# List all services (including inactive)
systemctl list-units --type=service --all
# List failed services
systemctl --failed
# Show service dependencies
systemctl list-dependencies nginxService Logs
# View logs for a service
journalctl -u nginx
# Follow logs in real-time
journalctl -u nginx -f
# Show last 50 lines
journalctl -u nginx -n 50Creating a Custom Service
Create /etc/systemd/system/myapp.service:
[Unit]
Description=My Application
After=network.target
[Service]
Type=simple
User=www-data
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/start.sh
Restart=on-failure
RestartSec=5
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reload
sudo systemctl enable --now myappUseful Tips
systemctl daemon-reload— run after editing any .service filesystemctl mask— completely prevent a service from startingsystemctl cat nginx— view the service file contentssystemctl edit nginx— create an override file