Advanced · 12 min · practise every command in the built-in terminal

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

SectionPurpose
[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

Practice tasks

  1. Create a service unit file at /etc/systemd/system/myapp.service using nano
  2. Reload systemd so it picks up the new unit file
  3. Enable and start your new service in one step
  4. Check the status of your new service

Commands in this lesson

Services & systemd