Basically we start our nodejs application using node command. What will happen if our system crashes or there is reboot in the system? Our node application will be stopped and it will not run. So again we have to start it manually using the node command.
PM2 is a nice package which solves this problem for us. We can use it to automatically start our node application after the system reboot or restart. If you do not have PM2 installed in your server please install it first. So what PM2 does is, it saves the node processes that we started and on system reboot, it will start the process again.
Please follow below 3 simple processes for implementing it.
- First of all, you need to enter following pm2 command
pm2 startup - Now start your node service using pm2. First of all go to root of your application and enter following command
pm2 start app.js --name=service-name - Now run following command to save the process
pm2 save
If you need to add another service then simply follow step 2 and 3, which will save all your node processes and pm2 will automatically restart the process whenever there is system reboot.
In step 2, app.js is the main file of your application which will run first. 'service-name' is your desired name for your application. It will help us to recognize the application process on pm2 list and pm2 log commands.
For more details please visit the official pm2 site: PM2 Startup Script