pm2 running multiple servers on same port

Viewed 2267

Using pm2 for the first time, I'm a bit confused about something. I'm running a very simple http server on port 1337 and using pm2 to run it:

var http = require('http');
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});
server.listen(1337);

and running it as follows:

pm2 start app.js

What I don't understand is, if I execute the above command (pm2 start app.js) several times, pm2 creates more instances of this app without any problem. But isn't there a conflict as all of them are listening on port 1337? And if not, what is the effect of multiple of them running at the same time? If a request comes in, which one does it go to?

Thanks

1 Answers

Assume you have already had a server running on port 1337
If you try to run another server on the same port, you should receive the following error

Error: listen EADDRINUSE 0.0.0.0:1337
    at Object.exports._errnoException (util.js:1036:11)
    at exports._exceptionWithHostPort (util.js:1059:20)
    at Server._listen2 (net.js:1252:14)
    at listen (net.js:1288:10)
    at Server.listen (net.js:1384:5)
    at EventEmitter.listen (/share/CE_CACHEDEV1_DATA/Web/radiationRepository/web/node_server/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/share/CE_CACHEDEV1_DATA/Web/radiationRepository/web/node_server/server.js:51:5)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)

This error will stop the node. For pm2, when it receives the exit signal, it should try to restart the server again and get the following logs

0|app      | Error: listen EADDRINUSE 0.0.0.0:1337
0|app      | Caught exception: Error: listen EADDRINUSE 0.0.0.0:1337
PM2        | App [app] with id [0] and pid [1167], exited with code [0] via signal [SIGINT]
PM2        | Starting execution sequence in -fork mode- for app name:app id:0
PM2        | App name:app id:0 online

I have skipped some logs here. Therefore, there should be only one server on port. PM2 will still accept the tasks and try to restart the server if there is this error.
You can run pm2 logs for finding the logs of pm2

Update: I have tried to run the same scripts with pm2. pm2 did not allow me to run the same script with several time unless I changed the files.

Related