PM2 is a process manager popular for managing node.js applications. It has built-in cluster, load-balancing and auto-restart support.

Install

Globally install pm2 module.

npm install pm2 -g

Run

Start, Daemonize and auto restart application.

pm2 start <entry_point>.js

Above we have started our application in fork_mode (1 instance) with an application name and process id used as reference to interact with our application with PM2. There is also a restart count, uptime and currently used memory. The restart count is useful in the case our node application hits an exception, fails fast, and dies so that PM2 can restart the instance and continue.

Cluster mode

PM2 comes with built-in cluster support that is smart enough to spin up one node process per CPU core using the following:

pm2 start app.js -i max

Using the -i flag and value max we can take advantage of PM2 dynamically spinning up one worker per core of our CPU. Here we see 8 instances of our application with a unique id and process id. We also get the benefit of PM2’s built-in load-balancer that will round robin requests. Remember all instances will be restarted by PM2 upon failures. More details on cluster mode here.

Monitoring

pm2 monit

To monitor our application we simply give the pm2 monit command that will show us the current CPU and memory usage per process. PM2 also has a max_memory_restart value on startup that can be applied to watch for memory usage and restart the process once it hits a certain threshold.

Logging

Managing logs with PM2 is not only easy, but one of it’s best features. With simple configuration you can rotate, merge, separate via file and timestamp and even compress or send notifications for your logs. Managing some of these features is available via JSON or other formatted configurations like so:

{
 “script” : “echo.js”,
 “error_file” : “err.log”,
 “out_file” : “out.log”,
 “merge_logs” : true,
 “log_date_format” : “YYYY-MM-DD HH:mm Z”
}

Conclusion

This is just a quick and simple overview of what PM2 can do for managing your node application. There is a full-blown dashboard in keymetrics.io, a module community for extending it’s capabilities, and amazing documentation. It’s worth a test run!