How to Run a Node.js App as a Background Service ?

Running a Node.js application as a background service is a common requirement for ensuring that your app stays running even after you log out, or if the system restarts. This can be particularly important for server-side applications, APIs, or any long-running processes. This article explores several methods to run a Node.js app as a background service, including using systems on Linux, PM2 process manager, and creating a Windows service.

To run a node.js app as a background service is to even after closing the node terminal, the app server needs to be kept running.

Table of Content

  • Using forever
  • Using systemd on Linux
  • Using nohup

Using forever

The easiest method to make a Node.js app run as a background service is to use the forever tool. forever is a simple Command Line Interface (CLI) tool that ensures that a given script runs continuously without any interaction.

Installation:

npm install forever -g

Example of Installation of forever

Command to Start forever

To start the forever tool, run the following commands replacing <app_name> with the name of the node.js app.

forever start /<app_name>/index.js

Example of Starting forever

Using systemd on Linux

Another method involves creating a service file and manually starting the app and enabling the service to keep it running in the background. This method uses systemd, a system and service manager for Linux operating systems.

Step 1: Create a new file <app_name>.service file replacing <app_name> with the name of the node.js app. Inside the files, enter the following values

ExecStart=/var/www/<app_name>/app.js
Restart=always
User=nobody
Group=nogroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/<app_name>

Step 2: After configuring the service file,Copy the <app_name>.service file into the /etc/systemd/system.

Step3: Start the app with the following command to make it run with the service file:

systemctl start <app_name>

Using nohup

Another method to run a Node.js app as a background service is by using the nohup command. nohup is a Unix command that allows a process to continue running in the background after the user has logged out.

Run the following command to start the nohup replacing the <app_name> with the name of the node.js app:

nohup node /<app_name>/index.js &

The nohup command does not terminate this process even then the command terminal is closed.

Example of using nohup