
How to Create a systemd Service on Linux
By Trenton Barrett on March 27, 2025 (Last updated: March 27, 2025)
How to Create a systemd Service on Linux
systemd
is the init system used by most modern Linux distributions to bootstrap the system and manage services. With systemd, you can create custom service units to control your own applications, scripts, or background tasks.
Common Uses for systemd Services
- Run applications on boot (like a Node.js app, game server, etc.)
- Keep a background script always running and restarted on failure
- Control custom daemons with
start
,stop
,restart
, andstatus
commands
Step 1: Create Your Script or Application
First, make sure you have a script or application ready to be run. For example, a simple bash script:
#!/bin/bash
echo "Service started at $(date)" >> /var/log/my-script.log
sleep infinity
Save this file as /usr/local/bin/my-script.sh
and make it executable:
sudo chmod +x /usr/local/bin/my-script.sh
Step 2: Create the systemd Service File
Create a unit file in /etc/systemd/system
. We'll call it my-script.service
:
sudo nano /etc/systemd/system/my-script.service
Paste the following contents:
[Unit]
Description=My Custom Script
After=network.target
[Service]
ExecStart=/usr/local/bin/my-script.sh
Restart=always
User=root
[Install]
WantedBy=multi-user.target
Step 3: Enable and Start the Service
Reload systemd to recognize the new service, then enable and start it:
sudo systemctl daemon-reexec
sudo systemctl daemon-reload
sudo systemctl enable my-script.service
sudo systemctl start my-script.service
Check the status to confirm it’s running:
sudo systemctl status my-script.service
Step 4: Managing Your Service
You can control your service just like any systemd unit:
sudo systemctl stop my-script.service
sudo systemctl restart my-script.service
sudo journalctl -u my-script.service
The last command lets you view logs produced by the service.
Conclusion
Creating a custom systemd service is a powerful way to automate and control long-running applications or scripts. Once set up, you gain full control over startup, restart behavior, logging, and monitoring — making it perfect for developers, sysadmins, and self-hosters.