giovedì 21 maggio 2015

Simple cluster of nodejs app

It is pretty simple to start your app.js in a cluster assigning 1 core to 1 nodejs process:

1) Install the cluster module into your nodejs project directory:

npm install cluster

2) Create a file cluster.js with this code in the same directory of you app.js:

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {

  for (var i = 0; i < numCPUs; i++) {
    console('start on CPU#'+i);
    cluster.fork();
  }
  cluster.on('exit', function(worker, code, signal) {
    console.log('exit process#' + worker.process.pid);
  });

} else {

  //Point to your app.js here:
  require("./app.js");

}

3) start the app.js in cluster mode:

node cluster.js