Follow @devcrafter91

How to setup Node.js For production using systemd

Fri Apr 05 2019 nodejs systemd linux


Node.js is an open source runtime based on the Google's V8 engine and it's consider the most easy, fun and flexible tool for developers for building web apps. Using Typescript for Node.js will make your code of course less buggy, object oriented and typed.
Running Node.js as a service can be done easily with PM2 but it's unnecessary cause systemd is also easy to setup a service and considered way more stable and flexible than PM2.

How to configure a basic Node.js systemd service

First of all create a file under /etc/systemd/system/ using the systemd's syntax for example /etc/systemd/system/nodejs-test-app.service.

Description=My first Nodejs Service

ExecStart=/usr/bin/node main.js


Tip: Service should always have the .service extension.


There are tons of params that could affect the service but the most basic and commonly used are the following:

Description: Gives a nice & clean description about your app for better logging.
After: Ensures that service will run after the network is up and running.
Environment: Specify the env vars that are going to be passed in the app. Node.js can handle those vars using process.env
Type: Affects the ExecStart behavior.
User: Specify which user will run the app.
WorkingDirectory: Define the working environment of the app.
ExecStart: Specify the program that is going to be launched.
Restart: Control the behavior during failure.
StadardOutput, StadardError: Specify the logging management.

How to enable and start services in systemd

After creating the service, systemd daemon must be reloaded using the command systemctl daemon-reload. Enabling the service can be done using systemctl enable followed by the file name of the service. For example systemctl enable nodejs-test-app.service will make the Node.js app run during startup every time system boots.
Starting the service is also easy, can be done using systemctl start nodejs-test-app.service.

Logging & debugging

Systemd provides a tool called journalctl which prints out every log collected by systemd. Fetching every logs for the app can be done by passing the -u argument followed by the file name of the service.
For example journalctl -u nodejs-test-app.service

Tip: Get real time log updates using the follow parameter -f. For example journalctl -f -u nodejs-test-app.service