Follow by Email

NodeJS Scaling - Working with clusters using PM2


In the real world, there are already many tools that we can use to help us manage clusters in production.  PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks. It will allow you to manage zero down time clusters in production. 



Using PM2:
1)      Install pm2 using command “sudo npm install -g pm2”. 

2)      Start an application to start any application ( Node.js, Python, Ruby, binaries in $PATH...) like that :
  $ pm2 start app.js

In app.js:

const http = require('http')
const options = [
    "Do it",
    "Don't do it"
]

const server = http.createServer((req, res) => {
    const randomIndex = Math.floor(Math.random() * options.length)
    const advice = options[randomIndex]
    const payload = JSON.stringify({
        processID: process.pid,
        advice
    })
    console.log(`advice from ${process.pid}: ${advice}`)
    res.writeHead(200, { 'Content-Type': 'application/json'})
    res.end(payload)
})

server.listen(3000)
console.log(`advice service running`)


3)      To list all running applications:
$ pm2 list

4)      To monitor logs, custom metrics, application information:
$ pm2 monit

There are already great tools out there that we can use. Also, cloud services like AWS or Roku, Cloud flair, or Azure have tools that manager clusters baked into their environments. It's important to know that sheer no JS websites at API will run in production on many instances and they never have to go down.