systemd is the standard system and service manager for most modern Linux distributions. It controls how services start, stop, and interact. Learning how to use systemd to manage services like Apache, custom scripts, and scheduled jobs (timers) can greatly improve the maintainability and reliability of your servers.
Understanding systemd Units
A unit is the basic object in systemd. The most common types are:
- service: For running and managing system services (like Apache).
- timer: For scheduling tasks like cron jobs.
- target: For grouping units and controlling boot order.
Managing Existing Services (e.g., Apache)
Apache is typically managed as a systemd service. Common commands:
# Start Apache service
sudo systemctl start apache2 # On Debian/Ubuntu
sudo systemctl start httpd # On RHEL/CentOS/Fedora
# Enable service to start at boot
sudo systemctl enable apache2
# Check the service status
sudo systemctl status apache2
Replace apache2
with httpd
on Red Hat-based systems.
Creating a Custom systemd Service
To run a custom script as a service, create a new unit file:
- Create your script, e.g.,
/usr/local/bin/myscript.sh
. - Make sure it’s executable:
chmod +x /usr/local/bin/myscript.sh
- Create the unit file
/etc/systemd/system/myscript.service
:
[Unit]
Description=My Custom Script Service
[Service]
ExecStart=/usr/local/bin/myscript.sh
Restart=on-failure
[Install]
WantedBy=multi-user.target
- Reload systemd and start your service:
sudo systemctl daemon-reload
sudo systemctl start myscript
sudo systemctl enable myscript
Using systemd Timers for Scheduled Jobs
systemd timers are a powerful alternative to cron.
- Create a service unit, e.g.,
/etc/systemd/system/backup.service
:
[Unit]
Description=Run Backup Script
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
- Create a timer unit, e.g.,
/etc/systemd/system/backup.timer
:
[Unit]
Description=Run backup every day at midnight
[Timer]
OnCalendar=*-*-* 00:00:00
Persistent=true
[Install]
WantedBy=timers.target
- Enable and start the timer:
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
Check timer status with:
systemctl list-timers
Conclusion
Using systemd to manage services, scripts, and scheduled tasks gives you more control and better integration with your Linux system compared to traditional tools. Embrace it to streamline your server management workflow.
Leave a Reply