Node.js process manager

Installation via NPM is simple:

$ npm install pm2 -g
											

 To make PM2 start automatically after a server reboot, execute the following statement after installation:

 $ pm2 startup
											

Depending on your OS, the above command will give you additional instructions, usually a one liner which you can copy/paste and run as root to add PM2 to the startup scripts. Now you're ready to use PM2! To add a node.js process, you can either create a JSON file for your microservice, or you can also add it directly from the command line. A PM2 process JSON file for your node.js app could look like this:

{
  "apps" : [{
    "name"       : "my-app",
    "watch"	 : false,
    "script"     : "server.js",
    "instances"  : 1,
    "exec_mode"  : "fork"
  }]
}
											

The file can have any name you want, I usually name it pm2-process.json. To add the process to the PM2 manager:

 $ pm2 start pm2-process.json
											

In this sample only one process will be started, because we defined instances=1 and exec_mode=fork. PM2 comes with built-in clustering support, if you want to launch more than once instance, set exec_mode to cluster and specify how many processes should be launched. You can also use instances= -1 to launch as many processes as you have CPU cores, minus one.

{
  "apps" : [{
    "name"       : "my-app",
    "watch"	 : true,
    "script"     : "server.js",
    "instances"  : 3,
    "exec_mode"  : "cluster"
  }]
}
											

In the example above, watch is set to true, this will automatically restart the process when changes on the file system are detected, e.g. if you pull a new version of your node.js server code from a git repo. So you don't have to ssh into your server after automatic deployment of changes. After adding all your node.js processes to PM2, you should save the process list so all your processes will be restored after a server reboot. To save the process list:

 $ pm2 save
											

To list all processes and statistics:

 $ pm2 list
											

To view logs:

 $ pm2 logs

or for a specific process:

 $ pm2 logs {app name or id}
											

You can also get an overview screen using:

$ pm2 monit
											

To stop or start a process:

 $ pm2 start {app name or id}
 $ pm2 stop {app name or id}
											

Kommentar einfügen: