pm2, node, instances and ports
Asked Answered
A

3

9

Sorry if this question is to 'newbie' but I can't see how to do it / how it works.

1/ I am creating an API using node.js, API serving some front apps

2/ To get it robust I use pm2 (great product), having nginx as proxy, fine

3/ But how could I handle multiple instance of my node.js api ? I see the 'cluter mode', fine, but what's happening while my node.js is listening on a single port (8080 for instance) ? If I configure 4 process / instances, they just can't all listen on the same port ah the same time ? ... so : do pm2 dispatch the calls between the instances (so acting as a kind of proxy indeed).

Any clue will be appreciated, how does it work ?

Greg

Angieangil answered 24/5, 2017 at 23:46 Comment(0)
G
9

Node in cluster mode creates one master and then spawns worker process which share TCP connection so basically load is distributed among workers.

Here is a beautiful article which elaborates both pm2 and node cluster -

https://getstream.io/blog/running-pm2-node-js-in-production-environments/

Hope it helps.

Gabey answered 25/5, 2017 at 7:18 Comment(3)
but how could I handle session variables between threads ? Is that handled automatically or do I have to use something to handle it (memcahe maybe?)Angieangil
Hi, I answer my question : I have to handle sessions by myself, mode does not handle session sharing, so identification, info between pages ... hs to be handled manualy between callsAngieangil
Yes, one has to handle shared variables from own implementation. I normally prefer a combo of Redis and Mongo. It depends from use case to use case.Gabey
P
1

You can manage load using nginx also. here is the documentation for nginx load balance

after that you can run app with specific port using environment variable from .env file and access it like this way. ex: process.env.PORT

after that run app using pm2 this way

PORT=5003 pm2 start routes.js --name app5003
PORT=5002 pm2 start routes.js --name app5002
PORT=5004 pm2 start routes.js --name app5004
Parameter answered 24/11, 2021 at 17:31 Comment(0)
A
0

Thanks all for your answers, So, from all the tips you gave me :

  • I have to handle by myself sessions and variables between threads,
  • pm2 cluster mode is the right way
  • pm2 will dispatch calls between instances, let's say in a round robin way

Case closed, again thank you very much for all your tips and answers yu provided, you save me a great bunch of time.

Angieangil answered 27/5, 2017 at 17:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.