systemd

systemd

Let's imagine the file server.js which, when executed by Node.js, serves web pages to connecting clients. A trivial way to execute server.js using NodeJS would be to run the following bash command in a terminal:

node server.js

Here, Node.js will execute server.js as long as the user does not interrupt the process with Ctrl-C or ends the bash session.

However, this last point can cause problems. What if we want to continue serving web pages even after exiting the bash session? Basically, what we want is server.js to be executed in the background. A method to do so is to execute of server.js as a service.

Service files

To execute a program as a service, a .service file needs to be created in /etc/systemd/system/. Here is a simple .service file for our corresponding example:

[Unit]
Description=My service
After=network.target

[Service]
User=yourusername
ExecStart=/usr/bin/node /home/yourusername/server.js

[Install]
WantedBy=multi-user.target

It is important to notice the line beginning with ExecStart, which specifies the command to be run as a service.

systemctl

Services are handled with a program called systemd (hence the path of the service files) and uses the command systemctl to start or stop services. For example:

sudo systemctl start myservice.service

Once started, a service will run until the computer is shut down. However, services can be made so as to start automatically at boot using the command systemctl enable:

sudo systemctl enable myservice.service

Finally, to check if a service is running, the command systemctl status can be used:

sudo systemctl status myservice.service

Automatic restart of services upon failure

Services are commonly meant to be left running without supervision. However, services can crash and would require being restarted manually. However, services can be configured to as to automatically by adding the lines Restart=always and RestartSec=3 in the service file as such:

[Unit]
Description=My service
After=network.target

[Service]
User=yourusername
Restart=always
RestartSec=3
ExecStart=/usr/bin/node /home/yourusername/server.js

[Install]
WantedBy=multi-user.target

Here, RestartSec is used to delay the restart a little so as to not crash repeatedly too often.

Remarks

Although using systemd can be used to run applications in the background, there are better ways to deploy web applications. For instance, Kubernetes has become an industry standard for the orchestration of applications.