This is a guide on how to create, manage and persist your own systemd service.
But first — what is a system service?
- A system service is a background process managed by the operating system.
- It typically handles essential tasks like networking, logging, or scheduling.
- Services are controlled by a service manager — on most Linux systems, that's
systemd
. - They can start automatically at boot, on demand, or based on specific triggers.
- You can use system services to automate tasks, such as running scripts at startup or restarting failed processes.
By the end of this guide you'll be able to:
- ✅ Create a simple bash script that runs continuously in the background
- ✅ Set up a systemd service to manage and automate that script
- ✅ Configure service behavior, including auto-restart on failure
- ✅ Redirect service output to a log file for monitoring
- ✅ Control the service using
systemctl
commands (start, stop, enable, disable, status) - ✅ Ensure your service starts automatically at boot
- ✅ Use systemd to automate tasks and maintain persistent background processes
🔧 Step by Step Guide
1. Create the Dummy Script
Create a file called dummy.sh
and add the following content:
#!/bin/bash
while true; do
echo "$(date) | Dummy service is running..." >> /var/log/dummy-service.log
sleep 10
done
Save the file and make it executable:
chmod +x dummy.sh
Copy the file to the proper directory:
sudo mv dummy.sh /usr/local/bin/dummy.sh
2. Create the Systemd Service File
Create a new systemd service file:
sudo vi /etc/systemd/system/dummy.service
Add the following content:
[Unit]
Description=Dummy service
After=network.target
[Service]
ExecStart=/usr/local/bin/dummy.sh
Restart=always
User=root
StandardOutput=append:/var/log/dummy-service.log
StandardError=append:/var/log/dummy-service.log
[Install]
WantedBy=multi-user.target
Also make sure to set the log file permissions properly to avoid systemd errors:
sudo touch /var/log/dummy-service.log
sudo chmod 644 /var/log/dummy-service.log
3. Reload Systemd and Enable the Service
Run these commands to apply the changes:
sudo systemctl daemon-reload
sudo systemctl enable dummy
4. Manage the Service
You can interact with the service using:
sudo systemctl start dummy # Start the service
sudo systemctl stop dummy # Stop the service
sudo systemctl enable dummy # Enable the service to start on boot
sudo systemctl disable dummy # Disable the service
sudo systemctl status dummy # Check the service status
5. Check Logs
Check your log file:
cat /var/log/dummy-service.log
6. Ensure the Service Auto-Restarts
If the service crashes, Restart=always
ensures it restarts.
Top comments (0)