PM2 Introduction

· 7 min read

Original English repository URL: Click here

PM2 is a production-grade process manager for Node.js applications with built-in load balancing. It ensures applications stay running continuously, enables zero-downtime restarts, and makes it easy to manage these system tasks. Starting an application in production mode is very simple, like this: $ pm2 start app.js PM2 works on Linux (stable), macOS (stable), and Windows (stable).

Installing PM2

$ npm install pm2 -g The npm command comes with Node.js when you install it - Install Node via NVM

Updating PM2

# Install the latest version of PM2
$ npm install pm2 -g
# Save the process list, exit the old PM2, and restore all processes
$ pm2 update

PM2 updates seamlessly.

Main Features

Command Reference

# Common commands
$ npm install pm2 -g            # Install PM2
$ pm2 start app.js              # Start application, automatically restart if it crashes (Node)
$ pm2 start app.py              # (Python)
$ pm2 start npm -- start        # 

# Cluster mode (Node.js only)
$ pm2 start app.js -i 4         # Cluster mode, start 4 application instances
                                # Load balancing based on network requests
$ pm2 reload all                # Zero-downtime restart
$ pm2 scale [app-name] 10       # Scale cluster app processes to 10

# Process monitoring
$ pm2 list                      # List all applications started with PM2
$ pm2 monit                     # Display memory and CPU usage for each application
$ pm2 show [app-name]           # Show all information about an application

# Log management
$ pm2 logs                      # Display logs for all applications
$ pm2 logs [app-name]           # Display logs for a specific application
$ pm2 logs --json               # Display logs in JSON format
$ pm2 flush
$ pm2 reloadLogs

# Process state management
$ pm2 start app.js --name="api" # Start application with name "api"
$ pm2 start app.js -- -a 34     # Start application with parameter "-a 34"
$ pm2 start app.js --watch      # Restart application when files change
$ pm2 start script.sh           # Start bash script
$ pm2 start app.json            # Start all applications declared in app.json file
$ pm2 reset [app-name]          # Reset application counters (restart counts)
$ pm2 stop all                  # Stop all applications
$ pm2 stop 0                    # Stop application with ID 0
$ pm2 restart all               # Restart all applications
$ pm2 gracefulReload all        # Graceful reload of all applications in cluster mode
$ pm2 delete all                # Stop and delete all applications
$ pm2 delete 0                  # Stop and delete application with ID 0

# Startup management
$ pm2 startup [platform]        # Detect init system, generate and configure PM2 startup script
$ pm2 save                      # Save current process list
$ pm2 resurrect                 # Restore previously saved processes
$ pm2 unstartup                 # Disable and remove startup script

$ pm2 update                    # Save processes, stop and restore processes
$ pm2 generate                  # Generate a sample JSON configuration file

# Deployment
$ pm2 deploy app.json prod setup    # 
$ pm2 deploy app.json prod          # 
$ pm2 deploy app.json prod revert 2 # 

# Module system
$ pm2 module:generate [name]    # Generate sample module with specified name
$ pm2 install pm2-logrotate     # Install module (includes a logging system)
$ pm2 uninstall pm2-logrotate   # Uninstall module
$ pm2 publish     

Process Management

Once applications are started, you can easily list and manage them

List all running processes $ pm2 list Directly manage your processes

$ pm2 stop     <app_name|id|'all'|json_conf>
$ pm2 restart  <app_name|id|'all'|json_conf>
$ pm2 delete   <app_name|id|'all'|json_conf>

Load Balancing and Zero-Downtime Restart

When starting an application with the -i <instance_option> option, cluster mode is enabled. In cluster mode, applications automatically balance requests, and this mode allows you to flexibly improve performance based on the number of CPU cores. Supported by all major Node.js frameworks and any Node.js application without requiring any code changes.

Main commands

$ pm2 start app.js -i max  # Enable load-balancer and start 'max' instances (cpu nb)

$ pm2 reload all           # Zero second downtime reload

$ pm2 scale <app_name> <instance_number> # Increase / Decrease process number

More information about using clustering with PM2

Logging Capabilities

Display logs for specific processes or all processes, real-time, standard, raw, JSON and formatted output

$ pm2 logs ['all'|app_name|app_id] [--json] [--format] [--raw]

Examples:

$ pm2 logs APP-NAME       # Display APP-NAME logs
$ pm2 logs --json         # JSON output
$ pm2 logs --format       # Formatted output

$ pm2 flush               # Flush all logs
$ pm2 reloadLogs          # Reload all logs

Startup Script Generation

PM2 can generate and configure startup scripts so that PM2 and your processes can remain running after each server restart. Supported init systems include: systemd (Ubuntu 16, CentOS, Arch), upstart (Ubuntu 14/12), launchd (macOS, Darwin), rc.d (FreeBSD).

# Auto detect init system + generate and setup PM2 boot at server startup
$ pm2 startup

# Manually specify the startup system
# Can be: systemd, upstart, launchd, rcd
$ pm2 startup [platform]

# Disable and remove PM2 boot at server startup
$ pm2 unstartup

Save process list at restart $ pm2 save More about startup scripts

Module System

PM2 includes a simple yet powerful module system, making it straightforward to install modules. $ pm2 install <module_name> Here are some compatible modules (standalone Node.js applications managed by PM2):

pm2-logrotate auto rotate logs of PM2 and applications managed pm2-webshell expose a fully capable terminal in browsers pm2-server-monit monitor your server health

Write your own module

Keymetrics Monitoring

If you use PM2 to manage your Node.js apps, Keymetrics makes it easy to monitor applications through the server. Thank you, hope you enjoy PM2!

More Resources About PM2

Changelog

CHANGELOG

Contributors

Contributors

Frequently Asked Questions

The following issues are not clearly documented in the official documentation but are commonly encountered in practical use. Here are some explanations.

Why does pm2 list sometimes not display appid and other information?

This mainly depends on the terminal window size, as shown in the image below:

pm2 list

You’ll notice that two executions display different information in the window. The actual reason is that during the first execution, my terminal window was very narrow. After enlarging it and executing the command again, it displays the information shown at the bottom. So to display complete application information, you need to ensure the terminal window is large enough.

How to restart, stop, and manage multiple applications?

For example, if we have applications with appid 0 and 1, besides operating on individual applications or all applications, PM2 actually supports multiple applications. The operation method is as follows: pm2 start 0 1 - this will start applications with IDs 0 and 1. The same applies to stop, restart, and other operations.

Are PM2 application logs necessary?

Generally, applications managed by PM2 have their own logging systems. For example, when developing Node.js applications, I typically use log4js, so PM2’s logging output is unnecessary and should be disabled.

Environment variables undefined after PM2 startup

Recently, there was a need to call environment variables in web applications. It was discovered that when Node starts normally, environment variables are obtained correctly, but when started with PM2, they are reported as undefined.

Solution: add the parameter --env production

Final Thoughts

PM2 is an essential tool for any Node.js developer working in production environments. Its ability to manage processes, provide zero-downtime deployments, and handle load balancing makes it invaluable for maintaining robust applications. The key benefits include:

  • Process management: Easy start, stop, restart, and monitoring of Node.js applications
  • Cluster mode: Built-in load balancing across multiple CPU cores
  • Zero-downtime deployments: Seamless application updates without service interruption
  • Log management: Comprehensive logging capabilities with various output formats
  • Startup scripts: Automatic configuration to keep applications running after server reboots
  • Module ecosystem: Extensible through various community modules

While PM2 provides excellent logging capabilities, it’s worth considering whether you need them if your application already has a robust logging system like log4js. The environment variable issue is a common gotcha, but easily resolved with the --env parameter.

Overall, PM2 significantly simplifies Node.js application deployment and management in production environments, making it a must-have tool for serious Node.js development.