shay1591's avatar

how to reverse proxy the same ip to the same pm2 cluster with nginx

Hello

I made a laravel app where the frontend connects to my nodejs server via websocket. Both my laravel app and nodejs server reside on the same hosting server and talk internally with eachother. Internally I receive this traffic via nginx and reverse proxy it to where the nodejs server resides.

Now this nodejs server uses in memory maps which holds data about the connected users, one of the logic rules is that a user can only connect once, after connecting again with another tab or device the previous connection to nodejs and the websocket is aborted.

Now here is where the problem starts, I use pm2 to manage this nodejs server and I use it in cluster mode because I have multiple cpus on my hosting server so it seemed the best thing to do. Now because I was so stupid to create this nodejs server with using in memory data neither of these clusters made by pm2 know about eachoter's data so a user can basically connect 2 times before being disconnected.

So I dont really know what to do here, I tried setting up the sockets on different ports and then route to these ports with nginx but that did not work, pm2 seems to serve them on the same port somehow? is it possible to do this purely with nginx and if so how? or Should i just bang my head on the wall and rewrite the nodejs server to use redis for state as I should have done in the first place lol

0 likes
1 reply
Glukinho's avatar

I think you need this: https://pm2.keymetrics.io/docs/usage/cluster-mode/

Statelessify your application Be sure your application is stateless meaning that no local data is stored in the process, for example sessions/websocket connections, session-memory and related. Use Redis, Mongo or other databases to share states between processes.

Change your connections storage from in-memory to something persistent and available to all processes.

I can't imagine how it can be achieved with nginx.

Please or to participate in this conversation.