How to Create and Start Systemd Service File for Anything from Web Backend to Bash Script
Systemd is native and installed to many Linux distribution both for open source and enterprise solution.
Forgot the
nohup
hack and start to run the real service. There is nothing hard.
Step 1: Create Service File
The file must be in the Systemd folder /etc/systemd/system/
For example, you create the file here in /etc/systemd/system/my-backend.service
with the following content
[Unit]
Description=My service description e.g., web backend
[Service]
User=ubu
WorkingDirectory=<directory_of_script e.g. /etc>
ExecStart=<script which needs to be executed>
# This is good part of running the service
# Monitor and restart when it is down
Restart=always
RestartSec=3
ExecStart is anything you want to run from Web, API backend, any server to Shell Script
For example Node.js, Go Executable, Spring JAR, PHP, any Service that listen TCP/UDP, Bash script, auto connection script etc.
Step 1.5: Analyze the file to check for error
It is hard to see what wrong what your file. This command will save hours spending trial and error to pinpoint the bug.
sudo systemd-analyze verify my-backend.service
Step 2: Make the Systemd know your script
sudo systemctl daemon-reload
Step 3: Start the Service
sudo systemctl start my-backend.service
Step 4: See log of the service
journalctl -u my-backend.service
journalctl -u my-backend.service--since="2024-01-01 18:00:00"