Skip to content
RIPE NCC member · Local Internet RegistryCall us on 020 3318 3449sales@hosting-telecom.uk

Running your own program at startup: systemd

How to turn your own program into a service that starts automatically with the server and restarts if it crashes.

Contents

If your own program runs on the server — a bot, a job processor, a Node.js or Python website — set it up as a service. It will then start by itself after the server reboots, and come back up by itself if it crashes. The old way, adding a command to /etc/rc.local, doesn’t work by default on current systems.

The service file

Create the file /etc/systemd/system/mybot.service (use any name instead of mybot):

[Unit]
Description=My bot
After=network-online.target
Wants=network-online.target

[Service]
User=bot
WorkingDirectory=/opt/mybot
ExecStart=/usr/bin/python3 /opt/mybot/bot.py
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
  • User — the account the program runs as. It doesn’t usually need root, so create a separate user: sudo useradd -r -s /usr/sbin/nologin bot.
  • ExecStart — the start command, with full paths. command -v python3 will tell you where a program is — see Where is a program located.
  • Restart=on-failure — restart the program if it exits with an error.
  • Don’t write passwords and keys directly in the service file — put them in a separate file with permissions of 600 and include it with the line EnvironmentFile=/etc/mybot.env.

Starting it and checking

sudo systemctl daemon-reload          # re-read the service files
sudo systemctl enable --now mybot     # start it and enable autostart
systemctl status mybot                # is it running?
journalctl -u mybot -f                # what the program is logging (Ctrl+C to exit)

If you change the service file, run daemon-reload again, then sudo systemctl restart mybot.

On FreeBSD

The simplest way is a line in the user’s crontab (crontab -e). The system’s daemon program will restart the program if it crashes:

@reboot /usr/sbin/daemon -r -o /var/log/mybot.log /usr/local/bin/python3 /opt/mybot/bot.py

Didn’t find the answer? Ask our support team — we’ll help.

Choose which cookies we may use. You can change your mind at any time with the “Cookie settings” link at the bottom of every page.

Necessary

Always active

They keep the site secure and remember your cookie choice. They don’t identify you.

Google Analytics counts visits and shows which pages people find useful, so we can improve the site. Which cookies