Server

PM2

What is PM2?

PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, reload them without downtime, and facilitate common system admin tasks.

Optimized for Node.js; supports clustering and load balancing for better utilization of multi-core CPUs.


Install PM2

> npm install pm2@latest -g

Verify Installation

> pm2 --version

Use PM2

Switch to your project directory and run the following commands:

> pm2 start npm --name "project_name" -- start

With a specific port:

> PORT=3001 pm2 start npm --name "another_project_name" -- start

Run Your App in Cluster Mode

> pm2 start npm --name "project_name" -- start -i max

max means that PM2 will auto detect the number of available CPUs and run as many processes as possible.

Check Running Processes

> pm2 list

Enable Auto-Start

> pm2 startup

You should know!

After running the above command, you will see a command to run on your terminal to enable auto-start.

Save Current Processes

> pm2 save

If you need to remove init script via:

> pm2 unstartup systemd

Alternatively, you can remove the init script manually. The startup script is usually located in the systemd service folder /etc/systemd/system. You can identify the service name, which should be something like pm2-ubuntu.service.

> sudo systemctl stop pm2-ubuntu
> sudo systemctl disable pm2-ubuntu
> sudo rm /etc/systemd/system/pm2-ubuntu.service
> sudo systemctl daemon-reload

Utility Commands

Monitor CPU/Memory Usage

> pm2 monit

Restart All Processes

> pm2 restart all

Stop All Processes

> pm2 stop all

Delete All Processes

> pm2 delete all

Check Logs

> pm2 logs project_name

Clear Logs

> pm2 flush
Previous
Ngrok
Next
SSH