This guide applies to all modern Linux distributions that use systemd (Ubuntu, Debian, Fedora, CentOS, RHEL, Arch, etc.).

1. Prepare the application or script

Place the executable or script in a permanent location, such as /opt/myapp/ or /usr/local/bin/.

Example (a simple Python HTTP server):

sudo mkdir -p /opt/myapp
sudo nano /opt/myapp/server.py

Content of server.py:

#!/usr/bin/env python3
import http.server
import socketserver

PORT = 8000
handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), handler) as httpd:
    httpd.serve_forever()

Make it executable:

sudo chmod +x /opt/myapp/server.py

2. (Recommended) Create a dedicated system user

sudo useradd --system --no-create-home --shell /usr/sbin/nologin myappuser
sudo chown -R myappuser:myappuser /opt/myapp

3. Create the systemd unit file

sudo nano /etc/systemd/system/myapp.service

Standard unit file template:

[Unit]
Description=Example application service
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=myappuser
Group=myappuser
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/python3 /opt/myapp/server.py
Restart=always
RestartSec=5

# Optional security directives
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target

4. Activate the service

sudo systemctl daemon-reload
sudo systemctl enable myapp.service    # enable at boot
sudo systemctl start myapp.service     # start immediately

Or combine enable and start:

sudo systemctl enable --now myapp.service

5. Verify operation

sudo systemctl status myapp.service
journalctl -u myapp.service -f         # follow logs in real time

6. Common management commands

sudo systemctl start myapp.service
sudo systemctl stop myapp.service
sudo systemctl restart myapp.service
sudo systemctl reload myapp.service    # only if the program supports reload
sudo systemctl disable myapp.service

7. Modify settings safely (recommended method)

Instead of editing the main file directly:

sudo systemctl edit myapp.service

This creates an override file that persists across updates.

8. Open required ports (if the service listens on the network)

Ubuntu (ufw):

sudo ufw allow 8000/tcp

Fedora/RHEL/CentOS (firewalld):

sudo firewall-cmd --add-port=8000/tcp --permanent
sudo firewall-cmd --reload

The service is now installed, automatically started at boot, monitored, and will restart on failure.

By davs