Writing Your Own systemd Service
Unit files live in /etc/systemd/system/ and describe how to run and manage a program as a service.
A minimal service file
# /etc/systemd/system/myapp.service
[Unit]
Description=My Application
After=network.target
[Service]
ExecStart=/usr/bin/python3 /opt/myapp/app.py
Restart=on-failure
User=student
WorkingDirectory=/opt/myapp
[Install]
WantedBy=multi-user.target
Key sections
| Section | Purpose |
|---|---|
[Unit] | Description, ordering (After=, Requires=) |
[Service] | How to run it — ExecStart, Restart, User |
[Install] | When it should be enabled (WantedBy=) |
Restart policies
Restart=on-failure # Restart only if it exits with an error
Restart=always # Always restart if it stops
RestartSec=5 # Wait 5 seconds before restarting
Deploying it
sudo nano /etc/systemd/system/myapp.service # Create the file
sudo systemctl daemon-reload # Load the new unit
sudo systemctl enable --now myapp # Enable + start
systemctl status myapp # Verify
journalctl -u myapp -f # Watch its logs