Using PM2 to Restart a Job Following System Reboot

Posted By : Ishaan Madan | 12-Jan-2017

Server crash is developer's nightmare, we worry every moment that our server might fail and we in any position are forced to login via SSH into the system to re-start the jobs. Fortunately, The one using PM2 modules are lucky enough to have an effective solution for it.

PM2 comes with a default feature to create startup scripts for multiple initialized systems. These startup-scripts are executed whenever a system is booted which in turn restarts the PM2 process itself. This PM2 process restarts the listed jobs and helps in 
resumption of the applications running on the server.

User may create a startup-script by using PM2 auto-detection feature else he can even pass a particular initialization system name to the 
startup command. If a user is unaware of 
init system, then he may just execute pm2 startup command via command line without passing any arguments and let PM2 auto-detect.

pm2 startup  
# or
pm2 startup <init-system>  
# <init-system> is one of these options

The startup command will produce an output which is a command. The command needs to be executed with root permissions on the system via command-line.

$ pm2 startup
[PM2] Writing startup script in /etc/init.d/pm2-init.sh
[PM2] Making script booting at startup...
[PM2] -ubuntu- Using the command:
      su -c "chmod +x /etc/init.d/pm2-init.sh && update-rc.d pm2-init.sh defaults"

Execute the generated command to daemonize PM2 and generate the system’s init script which is executed on boot.

su -c "chmod +x /etc/init.d/pm2-init.sh && update-rc.d pm2-init.sh defaults"

This will produce the output.

Platform ubuntu  
Template  
#!/bin/bash
…
[PM2] Writing init configuration in /etc/init.d/pm2
[PM2] Making script booting at startup...
…
[DONE]
+---------------------------------------+
[PM2] Freeze a process list on reboot via:
$ pm2 save

Start Node.js Application

Thereafter, we need to start our application and save it with the start-up

$ pm2 start node app.js
[PM2] Starting server.js in fork_mode (1 instance)
[PM2] Done.
---------------------------------------------------------------------------------------------------
? App name ? id ? mode ? pid  ? status ? restart ? uptime ? cpu ? memory     ? watching ?
---------------------------------------------------------------------------------------------------
? node app.js   ? 0  ? fork ? 2065 ? online ? 0       ? 0s     ? 22% ? 6.664 MB   ? disabled

Saving Processes to Restart on System Boot

The last simply involves saving the jobs to the start-up script and is done using the following command.

$ pm2 save

Thanks

About Author

Author Image
Ishaan Madan

Ishaan is an experienced Wordpress/PHP Lead Developer, he has good knowledge of HTML, CSS, PHP, Wordpress, Jquery and AJAX. His hobbies are playing basketball and reading about defence.

Request for Proposal

Name is required

Comment is required

Sending message..