Node.js App Service Commands

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:
And add the following:
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:
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.