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.
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
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.
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.
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.
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/