Running a background app on Linux with a systemd service
A systemd unit file that's enough to run a background app on a Linux server, start it on boot, and restart it when it crashes.
Running an app with nohup ./myapp & or leaving it in tmux works, but when the server reboots the app doesn’t come back up, and nobody revives it when it crashes. Most Linux distributions on servers ship with systemd, so writing a service is the neatest option.
The unit file
Create the file /etc/systemd/system/myapp.service:
[Unit]
Description=myapp - API noi bo
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=60
StartLimitBurst=5
[Service]
Type=simple
User=deploy
Group=deploy
WorkingDirectory=/opt/myapp
EnvironmentFile=/etc/myapp/env
ExecStart=/opt/myapp/bin/myapp --port 8080
Restart=on-failure
RestartSec=3
[Install]
WantedBy=multi-user.target
A few things to note:
User=deploy: there’s no reason for the app to run as root.Restart=on-failure: restarts only when the app exits with an error. If the app exits normally (exit code 0), it’s left stopped, unlikeRestart=always.ExecStartmust be an absolute path. systemd doesn’t read thePATHfrom.bashrc.
The env file is made of KEY=value lines, with no export. It usually holds secrets, so remember to chmod 600 it:
DATABASE_URL=postgres://myapp:xxx@127.0.0.1/myapp
LOG_LEVEL=info
Enable the service and check the logs:
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
systemctl status myapp
journalctl -u myapp -f
Every time you edit the unit file you must run daemon-reload again, otherwise systemd keeps using the old version.
WorkingDirectory and restart limits
If you don’t set WorkingDirectory, the service runs from /. Any app that reads files by relative path (for example config.yaml) won’t find the file and will crash immediately, even though it runs fine when you start it by hand from the app’s directory.
Combined with the default RestartSec of only 100ms, systemd restarts the app over and over, hits the default limit (5 times in 10 seconds), and then stops for good. systemctl status will report:
myapp.service: Start request repeated too quickly.
myapp.service: Failed with result 'start-limit-hit'.
The root-cause error is usually buried among the restart lines at this point. Look at it with journalctl -u myapp -n 100 --no-pager. After fixing it, you have to run systemctl reset-failed myapp before you can start it again.
So always set WorkingDirectory, give RestartSec a few seconds, and set StartLimitIntervalSec/StartLimitBurst yourself in [Unit]. If you put them in [Service] by mistake, StartLimitIntervalSec is treated as an unknown key and ignored.
Check the unit file before deploying with systemd-analyze verify myapp.service, which catches mistakes such as a misspelled key name.