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:
$ 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:
// 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
npm install -g pm2
and is then used to run the JavaScript projects on your system, just like using the node
command:
pm2 start app.js
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.
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
You can stop a single server: pm2 stop app.js
or via index pm2 stop 0
Or all at once: pm2 stop all
.
You can delete a saved (cached) server configuration: pm2 delete app
or pm2 delete 0
.
Or all at once: pm2 delete all
.
Just like with Nodemon, you can reload the server on changes: pm2 app.js --watch
.
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
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.
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.
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.
Start by registering the app using the official guide.
Once linked with the official PM2 Keymetrics site, you should see your app metrics displayed.
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.
For everything else awesome, hit the follow button. Also, follow me on Twitter to stay up to date with my upcoming content.
Bye for now đź‘‹