Node.js PM2 Orchestration Explained
Tags: node, pm2, javascript, monitoring
Published: 2024-04-24 20:56:47

Meet Joe.
Joe is a Node.js developer who has just created an awesome Web application. He hosted a virtual machine (on AWS EC2, Digital Ocean, Linode, etc.), started an app (using `node app.js`), made himself a drink, and sat back to welcome the hordes of happy fans.

A few hours go by and customers begin to complain. The server seems to be struck by a lighting. It's no longer responding. 
Joe opens up a  VM, and Node.js is no longer running. No biggie, run `node app.js` again and the app is up and running again. 

A few more hours go by and the same issue occurs again. It was all running well in localhost, but the high traffic is causing the server to behave unexpectedly in production. What can Joe do?

## Enter **PM2**, the process manager for Node.js.

Process Managers enhance Node.js applications by allowing:
* monitoring the running services locally and in production
* running system administration tasks like (starting and stopping applications, without downtime) aka orchestration, 
* logging metrics
* load balancing, etc.

## Getting Started with PM2

To get started, create a simple server using Express.js:

```bash
$ npm init -y
...\Mirza\first-pm2-app\package.json:

{
  "name": "first-pm2-app",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

$ npm install express
```

With basic packages set up, create an app.js file and paste the following code:

```js
// app.js
const app = require('express')();

app.get('/', (req, res) => {
  res.send('hello world');
});

app.listen(3000, () => {
 console.log('Server started on port 3000!');
});
```
PM2 is an NPM package installed globally on the system 
```bash
npm install -g pm2
```
and is then used to run the JavaScript projects on your system, just like using the `node` command:

```bash
pm2 start app.js
```

![pm2-first-start](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8n2kr8xivmemie5wcl6.png)

Notice that we didn't get the log "Server started on port 3000!" printed as would normally happen when running `node app.js`.
Moreover, PM2 kicked us out of the long-running loop. If you go to the `localhost:3000`, you can verify that the server is up.

![localhost](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9pe8ko2oblnrigbx9twx.png)
The server is up and running in the back.

## How Can PM2 Fix Joe's Problems?

### Process Management

PM2 lets you manually start, list, and stop active processes.

You can list out the running PM2 servers: `pm2 list`

![pm2-list](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t5a2j6vc4zpxw1bnpfjm.png)

You can stop a single server: `pm2 stop app.js` or via index `pm2 stop 0`

![server-stop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3lk11cn7ivalxu3ya739.png)

Or all at once: `pm2 stop all`.

You can delete a saved (cached) server configuration: `pm2 delete app` or `pm2 delete 0`.

![pm2-delete](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bvncrdmssj5zce5dnvj7.png)

Or all at once: `pm2 delete all`.

Just like with Nodemon, you can reload the server on changes: `pm2 app.js --watch`.

![pm2-watch](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ly6f9b64a8z28j5lvgb.png)

### Self-Recovery
Instead of running the Node.js application via `node app.js`, use `pm2 start app.js`.  By running the app like this, PM2 will automatically recover the app from crashes - simply put, it automatically restarts the server if it fails.

### Scaling & Loadbalancing
By default, even if you're running the app on a multi-core CPU (server), Node.js runs an application on a single CPU core.
If you have high traffic it means that all requests are going to the single CPU instance while the rest are doing nothing.

The idea behind load balancing is to distribute the traffic across multiple cores:
* 2 `pm2 start app.js -i 2`
* 4 `pm2 start app.js -i 4`
* 8 `pm2 start app.js -i 8`
* all of them `pm2 start app.js -i max`

![running-pm2-on-multi-core-cpu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c3pcjowzqmyy3cu81mut.png)

Node.js uses a specific pattern for load balancing where all requests go to one core (master process) and if get occupied, it will automatically distribute the requests to other cores (processes). If the request count drops, so do the occupied cores.

![Imulti-core-server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xwcxtchleftflot8pkwb.png)

The result is an app that can handle large traffic.

### Monitoring & Logging

Running `pm2 monit app.js` lets you monitor the stats of your application (CPU & Memory Usage) as well as display logs in real time.

![pm2-monitoring](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ymg4kwv44xrbdgnudgq6.png)

Additionally, you can display logs per process or application:
* `pm2 logs <processname>` or 
* `pm2 logs <app-name>`


## PM2 Main App

PM2 lets you monitor metrics on their main website.

![pm2-site](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j1m8oziv3rh5fg85qd5a.png)

Start by registering the app using the [official guide](https://pm2.keymetrics.io/docs/usage/quick-start).

![registering-app-on-pm2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1r811p6vayn2glwc7ge9.png)

Once linked with the official PM2 Keymetrics site, you should see your app metrics displayed.

![pm2-metrics](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kz2yv3y9tvstuivs6u5n.png)

## Final Words

PM2 is a powerful process manager that helps you orchestrate your applications using a few commands, while you, like Joe, are resting on the beach somewhere in Hawaii. For more on PM2, be sure to check the [official docs](https://pm2.keymetrics.io/docs/usage/quick-start/). 

For everything else awesome, hit the follow button. Also, follow me on [Twitter](https://twitter.com/mirzaleka) to stay up to date with my upcoming content.

Bye for now 👋