I often have the need to run a piece of software as a daemon on Linux.

As I always tend to forget the exact syntax, I decided to write it down here.

The first step is to create a file in /etc/systemd/system/ with the extension .service (e.g. my-daemon.service).

[Unit]
Description=Runs myapp as a daemon

[Service]
Restart=always
WorkingDirectory=/var/www/working-dir
ExecStart=/var/www/working-dir/my-app
StandardOutput=append:/var/www/working-dir/stdout.log
StandardError=append:/var/www/working-dir/stderr.log
Environment="DATA_DIR=data"
Environment="PORT=3000"

[Install]
WantedBy=default.target

Once you have the file, you need to install it using the following commands:

$ sudo systemctl daemon-reload
$ sudo systemctl enable my-daemon.service
$ sudo systemctl start my-daemon.service

You can run the following commands to control the daemon.

$ sudo systemctl start my-daemon.service
$ sudo systemctl stop my-daemon.service
$ sudo systemctl restart my-daemon.service
$ sudo systemctl status my-daemon.service