In this post, we will see how can make a node app a systemd service.

Suppose you have built a Node.js application and you have been running it all the time with npm start or by using another application like nodemon, so that you don’t need to restart the server. That is acceptable for development, but once you want to deploy that application somewhere this becomes infeasible.

By deployment, we don’t always mean something big and serious like AWS, Heroku, Containers. We can also mean your laptop or PC, that you want to run your app seamlessly, without needing to explicitly commanding it.

Thats where systemd comes in, and helps as to make our app a service. This means that it can run by itself on system restart, have logging capabilities and we can control it with the usual systemctl commands as any other service in our system.

Create a unit file for systemd

To make our app a systemd service we need to create a unit configuration file named something like your_nodejs_app.service and we have to place it in /etc/systemd/system.

To create and open the unit file for editing, run:

sudo vim /etc/systemd/system/your_nodejs_app.service

And add the following:

[Unit]
Description=Your nodejs app description.

[Service]
ExecStart=/path/to/your_nodejs_app/index.js
Restart=always
User=nobody
# Note Debian/Ubuntu uses 'nogroup', RHEL/Fedora uses 'nobody'
Group=nogroup
# Needed only, for node installations with nvm
Environment=PATH=/usr/bin:/usr/local/bin:/home/$USER/.nvm/versions/node/v12.18.3/bin
Environment=NODE_ENV=production
WorkingDirectory=/path/to/your_nodejs_app/

[Install]
WantedBy=multi-user.target

The systemd unit file syntax and keywords can be found on the systemd.service man pages.

For a more extensive guide on systemd units, read Digital Ocean - Understanding Systemd Units and Unit Files.

Add the following line to your index.js

We must also add a shebang in our Node.js javascript entry point (e.g. index.js), indicating to systemd which environment should execute the program:

#!/usr/bin/env node

Fix unix-windows line endings

If we have developed the app under Windows, it is best to convert the line endings to Unix one’s. We can do this using the dos2unix utility or we can also do that on vim.

Open service file in vim

sudo vim myapp.service

Fix line endings

:set ff=unix

Save and quit

:wq

Make sure index.js is executable

chmod +x index.js

Restart systemctl to accept changes

sudo systemctl daemon-reload

Enable service

sudo systemctl enable your_nodejs_app

Start service

sudo systemctl start your_nodejs_app

See logs

sudo journalctl -u your_nodejs_app

For changes in source code to take effect

Restart service

sudo systemctl restart your_nodejs_app