With PM2, you usually do not need to use this design. This usually looks like this:
var cluster = require('cluster'); var http = require('http'); var os = require('os'); var numCPUs = os.cpus().length; if(cluster.isMaster){ for (var i = 0; i < numCPUs; ++i) { cluster.fork(); } } else { http.createServer(function(req, res) { res.writeHead(200); res.end("hello world"); }).listen(8080); }
With PM2 equivalent for above:
var http = require('http'); http.createServer(function(req, res) { res.writeHead(200); res.end("hello world"); }).listen(8080);
pm2 start app.js -i <number of instances>
you can read more on the topic here
Refresh . You can try to distinguish between master and slave by passing command line arguments. Example example.json:
{ "apps" : [ { "name": "Master", "script": "app.js", "args": ["master"], "instances": "1", }, { "name": "Slave", "script": "app.js", "args": ["slave"], "instances": "3" } ], ...
Then you can do the following:
argv = process.argv.slice(2) //stripe 'node', 'app.js' away if (argv[0] === 'master'){ // ... } else { // ... }
source share