Deploy Node.js app for production using systemd

Intro

Node.js is an open source cross platform runtime environment based on the Google’s V8 engine and it’s consider the most easy, fun and flexible tool for developers for building web applications. Using Typescript can make your Node.js app less buggy, object oriented and ofc you get all the juice of a structural typed language.
Running Node.js as a service can be done easily with PM2 but it’s unnecessary because systemd is considered way stable and flexible than PM2. You could scale your app across the cloud way more easily using systemd without depending on 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.

[Unit]
Description=My first Nodejs Service
After=network.target

[Service]
Environment=PATH=/usr/bin:/usr/local/bin
Type=simple
User=myuser
WorkingDirectory=/home/myuser/awesome-app
ExecStart=/usr/bin/node main.js
Restart=on-failure
RestartSec=60
SyslogIdentifier=awesome-app

[Install]
WantedBy=multi-user.target

Tip: Service should always have the .service extension.

Parameters

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.
SyslogIdentifier: App identifier.

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

Sources

https://www.freedesktop.org/software/systemd/man/systemd.service.html

https://nodejs.org/en

Follow me on Twitter! It's free!