Master the modern Linux service management with systemd. This comprehensive guide covers essential systemctl commands, service control, monitoring, troubleshooting, and creating custom systemd units for efficient daemon management.
What is systemd?
systemd is a system and service manager for Linux operating systems. It replaces the traditional SysV init system and provides:
- Parallel startup of system services
- On-demand activation of daemons
- Dependency-based service control
- Snapshot and restore capabilities
- Integrated logging with journald
- Socket activation for better resource management
1. Essential systemctl Commands
-f to follow logs in real-time.
--all to show inactive services too.
Service Status Commands in Detail
2. Service Management Scenarios
systemctl enable --now nginxsystemctl status nginx
journalctl -u nginx -xesystemctl reload nginxsystemctl mask nginxsystemctl reset-failed nginxsystemctl edit nginxJournalctl: Mastering System Logs
3. Creating Custom systemd Services
Basic Service Unit File
# /etc/systemd/system/myapp.service
[Unit]
Description=My Custom Application
After=network.target
Wants=network.target
[Service]
Type=simple
User=myappuser
Group=myappgroup
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/python3 /opt/myapp/app.py
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal
# Security hardening (optional)
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=/var/lib/myapp
[Install]
WantedBy=multi-user.target
Service Types Explained
Installation and Management Script
#!/bin/bash
# install-service.sh
# Creates and manages a custom systemd service
SERVICE_NAME="myapp"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
APP_PATH="/opt/${SERVICE_NAME}"
APP_USER="${SERVICE_NAME}"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${GREEN}=== Custom Service Manager ===${NC}"
case "$1" in
install)
echo -e "${YELLOW}Installing ${SERVICE_NAME} service...${NC}"
# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo -e "${RED}Please run as root${NC}"
exit 1
fi
# Create service file
cat > "$SERVICE_FILE" << EOF
[Unit]
Description=My Custom Application
After=network.target
[Service]
Type=simple
User=$APP_USER
Group=$APP_USER
WorkingDirectory=$APP_PATH
ExecStart=/usr/bin/python3 $APP_PATH/app.py
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
EOF
echo -e "${GREEN}Service file created: $SERVICE_FILE${NC}"
# Create application user if doesn't exist
if ! id "$APP_USER" &>/dev/null; then
useradd -r -s /bin/false "$APP_USER"
echo -e "${GREEN}Created user: $APP_USER${NC}"
fi
# Reload systemd
systemctl daemon-reload
echo -e "${GREEN}Systemd daemon reloaded${NC}"
# Enable and start service
systemctl enable "$SERVICE_NAME"
systemctl start "$SERVICE_NAME"
echo -e "${GREEN}Service installed and started${NC}"
systemctl status "$SERVICE_NAME"
;;
uninstall)
echo -e "${YELLOW}Uninstalling ${SERVICE_NAME} service...${NC}"
systemctl stop "$SERVICE_NAME"
systemctl disable "$SERVICE_NAME"
rm -f "$SERVICE_FILE"
systemctl daemon-reload
echo -e "${GREEN}Service uninstalled${NC}"
;;
status)
systemctl status "$SERVICE_NAME"
;;
logs)
journalctl -u "$SERVICE_NAME" -f
;;
restart)
systemctl restart "$SERVICE_NAME"
echo -e "${GREEN}Service restarted${NC}"
;;
*)
echo "Usage: $0 {install|uninstall|status|logs|restart}"
echo " install - Install and start the service"
echo " uninstall - Stop and remove the service"
echo " status - Check service status"
echo " logs - Follow service logs"
echo " restart - Restart the service"
exit 1
;;
esac
4. Advanced systemd Features
Timers: Systemd's Cron Replacement
# /etc/systemd/system/backup.timer
[Unit]
Description=Daily backup timer
[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=1h
[Install]
WantedBy=timers.target
# /etc/systemd/system/backup.service
[Unit]
Description=Database backup service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
User=backup
Socket Activation
# /etc/systemd/system/myservice.socket
[Unit]
Description=My Service Socket
[Socket]
ListenStream=8080
Accept=true
[Install]
WantedBy=sockets.target
# /etc/systemd/system/myservice@.service
[Unit]
Description=My Service Instance
[Service]
ExecStart=/usr/bin/myservice
StandardInput=socket
Troubleshooting Service Issues
1. Service fails to start: Check
journalctl -xe and verify paths/permissions2. Service starts but exits immediately: Check service Type and ExecStart command
3. Can't enable service: Check if service file is in correct location (/etc/systemd/system/)
4. Changes not taking effect: Run
systemctl daemon-reload after editing service files5. Permission denied: Check User/Group settings and file permissions
6. Dependency issues: Verify After= and Requires= directives
7. Resource limits: Check if service hits memory or CPU limits
8. Socket activation not working: Verify Accept=true and correct socket unit
5. systemd Cheat Sheet
Best Practices for systemd Services
- Always use
systemctl daemon-reloadafter editing service files - Set appropriate
UserandGroupfor security - Use
Restart=on-failurefor resilient services - Specify
WorkingDirectoryfor consistent file paths - Use
journalctl -u service -fto monitor logs in real-time - Test with
systemd-analyze verifybefore deploying - Use
systemctl editinstead of modifying original files - Set resource limits with
MemoryLimitandCPUShares - Use
Type=notifyfor services that need readiness notification - Regularly check
systemctl list-units --failed
Getting Started with systemd
Follow this learning path to master systemd:
- Learn basic commands: Start with
start, stop, restart, status - Master journalctl: Learn to filter and search logs effectively
- Understand unit files: Learn the structure of .service files
- Create custom services: Practice by creating simple service units
- Explore timers: Replace cron jobs with systemd timers
- Learn dependencies: Master
After=, Requires=, Wants= - Practice troubleshooting: Use the diagnostic commands regularly
- Study advanced features: Learn socket activation, resource control
- Create templates: Use service templates for multiple instances
- Stay updated: Follow systemd releases and new features
Master Modern Linux Service Management
systemd has revolutionized Linux service management with its powerful features and unified approach. By mastering systemctl commands and understanding service unit files, you gain complete control over your system's services.
Remember: systemd is not just an init system but a complete suite of system management tools. Take advantage of its logging, dependency management, and resource control features to build robust and maintainable systems.
Next Steps: Practice creating custom services for your applications. Convert existing init scripts to systemd units. Experiment with timers and socket activation. The more you work with systemd, the more you'll appreciate its power and flexibility.