How can we configure master process when using PM2
With PM2, you usually don't have to use this constuction. Typically, it looks like the following:
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 the equivalent for the above is:
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 up more on the topic here
Update: You can try to distinguish between master and slave by passing command line arguments. Here is an example ecosystem.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 {
// ...
}
If you're using PM2 >2.5 (i.e. after Jun 2017), you can use the NODE_APP_INSTANCE env variable:
if(process.env.NODE_APP_INSTANCE === "0") {
// the code in here will only be executed on the first instance in the cluster
}
// the code out here will be executed on all instances
This variable is only available in cluster mode. It counts up from zero for each new instance added. I'm not sure why it's a string rather than an integer.