Skip to content

Instantly share code, notes, and snippets.

@bewithdhanu
Last active April 17, 2023 10:50
Show Gist options
  • Save bewithdhanu/a392f61d35edf5eef8e27dc5b84753d0 to your computer and use it in GitHub Desktop.
Save bewithdhanu/a392f61d35edf5eef8e27dc5b84753d0 to your computer and use it in GitHub Desktop.
How to Start and Run a Node.js Service in the Background using PM2

How to Start and Run a Node.js Service in the Background using PM2

If you're running a Node.js service and want to keep it running in the background even after you log out, PM2 is a great tool to use. In this tutorial, we'll walk through the steps of starting and running a Node.js service in the background using PM2.

Step 1: Navigate to the Service Directory

First, navigate to the directory where your Node.js service is located. For example, if your service is located in /var/www/html/dandie/nodejs, you would navigate to that directory using the following command:

cd /var/www/html/dandie/nodejs

Step 2: Start the Service with PM2

Once you're in the directory where your Node.js service is located, you can start the service using PM2 with the following command:

pm2 start server.js

This will start your Node.js service and keep it running in the background.

Step 3: Set the Service to Run in the Background

To ensure that your Node.js service continues to run in the background even after you log out, you need to run the pm2 startup command. This will give you an output command that you need to run, which will look something like this:

sudo env PATH=$PATH:/usr/bin /usr/local/lib/node_modules/pm2/bin/pm2 startup systemd -u ubuntu --hp /home/ubuntu

Run this command in your terminal to set your Node.js service to run in the background.

Step 4: Save the Service Configuration

Finally, run the following command to save your service configuration:

pm2 save

This will save your Node.js service configuration so that it will automatically start when your server reboots.

That's it! You now know how to start and run a Node.js service in the background using PM2.

Bonus: Removing the Service from the Background

If you ever need to remove your Node.js service from the background, you can use the following command:

pm2 delete server

This will remove the server process from the background.

That's it! You now know how to start and run a Node.js service in the background using PM2, as well as how to remove it from the background if needed.

PM2 is a Production Process Manager for Node.js applications
     with a built-in Load Balancer.

Start and Daemonize any application:
$ pm2 start app.js

Load Balance 4 instances of api.js:
$ pm2 start api.js -i 4

Monitor in production:
$ pm2 monitor

Make pm2 auto-boot at server restart:
$ pm2 startup

To go further checkout:
http://pm2.io/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment