Automatically restart your Service with systemd

  1. Introduction
  2. Example with NodeJS

Introduction

I've searched for ways to automatically restart my application if it crashes, and have only found solutions which need extra software or something like 'forever'.
After a while I found out that you can do this with systemd, the init-process for most linux distrubutions nowadays.
This has 2 major advantages: It uses the internal journal for logging and it can easily be controlled with systemctl.

Example with NodeJS

Creating your own systemd service is quite easy, as it's only a file that you have to create.
An example:
First create your service file and add it to /etc/systemd/system. This example uses a NodeJS server, so the file could be named /etc/systemd/system/myapp.service
The Lines are pretty self-explanatory, but don't forget to change it to your own settings!
Contents of the .service file:

[Unit]
Description=My NodeJS Server

[Service]
ExecStart=/usr/bin/node /home/user/myapp/index.js
Restart=always
RestartSec=5
SyslogIdentifier=myapp
User=user
Group=user
Environment=NODE_ENV=production PORT=3000

[Install]
WantedBy=multi-user.target

Now we are ready to start it. Systemd services can be controlled using the systemctl command. It's quite easy to use:
sudo systemctl start myapp
This command simply starts your service. It will automatically restart 5 seconds after crashing thanks to our 6/7th line in the service files.
To automatically start your service on system startup simply run the following command:
sudo systemctl enable myapp
To check the status use status instead of enable. With stop you can stop the service, and to disable the auto-startup simply use disable instead of enable.

The status command also shows you an excerpt of the log. To see the full log use the journalctl command and look for your SyslogIdentifier, which in this case is myapp (which was set in the .service file)