How to use PM2 with Node.js
PM2 is a tool for managing Node.js processes, allowing for application clustering and load distribution across multiple CPU cores. It is mainly used for environments where you need to run a Node.js application and just "forget about it" (it can also be used with other languages).
I use a VPS hosting with pre-installed Ubuntu 20.04.3 LTS as an example. Keep in mind that there should be no significant difference for Node.js between recent versions of Ubuntu.
If you do not have Linux system, I'd recommend you to use Docker to create a Linux container for tests.
You will need to install Node.js and create a simple web application. These steps are described in this article.
The official guide suggests to install PM2 as a NPM or Yarn package:
sudo npm install pm2@latest -g
...
sudo yarn global add pm2
Let's find out how to run our test application via PM2.
Execute the following command:
sudo pm2 start /home/index.js
Results:
[PM2] PM2 Successfully daemonized
[PM2] Starting /home/index.js in fork_mode (1 instance)
[PM2] Done.
Let's check the list of applications and their cpu/memory usage:
sudo pm2 list
Results:
┌────┬────────────────────┬──────────┬──────┬───────────┬──────────┬──────────┐
│ id │ name │ mode │ ↺ │ status │ cpu │ memory │
├────┼────────────────────┼──────────┼──────┼───────────┼──────────┼──────────┤
│ 0 │ index │ fork │ 0 │ online │ 0% │ 46.4mb │
└────┴────────────────────┴──────────┴──────┴───────────┴──────────┴──────────┘
Use this command to stop all active applications:
sudo pm2 stop all
Or to stop a specific application (id = 0 for our case):
sudo pm2 stop 0
Results:
┌────┬────────────────────┬──────────┬──────┬───────────┬──────────┬──────────┐
│ id │ name │ mode │ ↺ │ status │ cpu │ memory │
├────┼────────────────────┼──────────┼──────┼───────────┼──────────┼──────────┤
│ 0 │ index │ fork │ 0 │ stopped │ 0% │ 0b │
└────┴────────────────────┴──────────┴──────┴───────────┴──────────┴──────────┘
Use the following command to make PM2 start automatically on the system boot so that all active node.js apps will be started automatically:
sudo pm2 startup systemd
To disable starting PM2 on the system boot:
sudo pm2 unstartup systemd
PM2 cheatsheet is available on this link.
You may also like