In this blog, we will learn how to start/restart the NodeJS server using PM2.
PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without the downtime and to facilitate common system admin tasks.
First, you need to have PM2 installed on your system/server globally.
$ npm install pm2 -g
Now you can run your node server from your project directory with your environment variables.
$ PORT=3000 ENV=production pm2 start app.js
This will save the process in PM2 with a particular ID. So whenever you want to start/restart/stop your server, you can specify the ID. e.g pm2 stop 1
Once you declare environment variables, PM2 saves those settings. You can’t change those settings until you shut down/reboot the server or delete the process. e.g. pm2 delete 1
The advantage of using PM2 is that if your server crashes for some reason, PM2 will automatically restart your application server. But for that, you need to follow the steps mentioned below:
- When your server restarts/reboot, make sure your MongoDB server also restarts automatically.
-
When you install MongoDB just run $ systemctl enable mongod.service on terminal.
This will make your MongoDB service auto-start on every system reboot. - Now to start NodeJS application server automatically on system restart/reboot, First, you have to startup pm2 with the following command and it will give you startup script command which you need to run from your terminal:
$ pm2 startup
- To set up the Startup Script, copy/paste the following command:
$ sudo env PATH=$PATH:/usr/bin /usr/local/lib/node_modules/pm2/bin/pm2 startup systemd -u username --hp /home/username
- It will generate a script in your terminal.
- Now start your server with your Environment variables and project name that you want to give:
$ PORT=3000 ENV=production pm2 start app.js --name <projectName>
- Now to Freeze a process list on reboot use following command:
$ pm2 save
- It will save the processes as below:
9. If you want to remove the init script, use this command:
$ pm2 unstartup systemd
Note: If your data is large then it might be a problem to connect to the database on system reboot. To avoid this issue you can add “auto_reconnect” functionality in your mongoose database connectivity.