Deploy Nodejs by Pm2

Depoly Nodejs Application with PM2

PM2 is simple and easy to use. http://pm2.io/

Install pm2

1
sudo npm install -g pm2

Start Application

The first thing you will want to do is use the pm2 start command to run your application, app.js, in the background:

1
pm2 start app.js

This also adds your application to PM2’s process list, which is outputted every time you start an application:
1
2
3
4
5
6
Output:
┌──────────┬────┬──────┬──────┬────────┬───────────┬────────┬────────────┬──────────┐
│ App name │ id │ mode │ PID │ status │ restarted │ uptime │ memory │ watching │
├──────────┼────┼──────┼──────┼────────┼───────────┼────────┼────────────┼──────────┤
│ app │ 0 │ fork │ 5871 │ online │ 0 │ 0s │ 9.012 MB │ disabled │
└──────────┴────┴──────┴──────┴────────┴───────────┴────────┴────────────┴──────────┘

As you can see, PM2 automatically assigns an App name (based on the filename, without the .js extension) and a PM2 id.
PM2 also maintains other information, such as the PID of the process, its current status, and memory usage.

Applications that are running under PM2 will be restarted automatically if the application crashes or is killed,
but an additional step needs to be taken to get the application to launch on system startup (boot or reboot).
Luckily, PM2 provides an easy way to do this, the startup subcommand.

The startup subcommand generates and configures a startup script to launch PM2 and its managed processes on server boots.
You must also specify the platform you are running on, which is ubuntu, in our case:

1
pm2 startup ubuntu

The last line of the resulting output will include a command (that must be run with superuser privileges) that you must run:
1
2
3
4
Output:
[PM2] You have to run this command as root
[PM2] Execute the following command :
[PM2] sudo su -c "env PATH=$PATH:/opt/node/bin pm2 startup ubuntu -u sammy --hp /home/sammy"

Run the command that was generated (similar to the highlighted output above) to set PM2 up to start on boot (use the command from your own output):
1
sudo su -c "env PATH=$PATH:/opt/node/bin pm2 startup ubuntu -u sammy --hp /home/sammy"

Other PM2 Usage

PM2 provides many subcommands that allow you to manage or look up information about your applications.

  • Stop an application with this command (specify the PM2 App name or id):
1
2
pm2 stop app
pm2 stop 0
  • Restart an application with this command (specify the PM2 App name or id):
1
2
pm2 restart app
pm2 restart 0
  • show pm2 managed apps list
1
pm2 list
  • More information about a specific application can be found by using the info subcommand (specify the PM2 App name or id)::
1
pm2 info example
  • monitor
1
pm2 monit
  • show app detail
1
2
pm2 show app
pm2 show 0
  • show app logs
1
2
pm2 logs app
pm2 logs 0