tlaverdure / laravel-echo-server

Socket.io server for Laravel Echo
MIT License
2.64k stars 509 forks source link

running echo server in pm2 cluster mode #520

Open mohamadchoker opened 4 years ago

mohamadchoker commented 4 years ago

Hello, I'm running the echo server using cluster mode and stress testing the server with a script that subscribes 10k users to the socket. It ends up with 7984 users connected to the socket and the odd thing that I'm monitoring pm2 and I can see that 1 node is working (increased CPU, memory) while other nodes' values do not change.

this my pm2 conf.json file:

`module.exports = { apps : [{ name : "echo", script : "server.js", args: "start", instances : "4", exec_mode : "cluster" }],

};`

Screenshot from 2020-05-12 15-41-18

markotitel commented 4 years ago

@mohamadchoker How does this addresses echo server? Have you tried some other Node app, maybe you did something wrong.

happyDemon commented 4 years ago

@mohamadchoker That's logical, the only thing cluster mode does, is run the same script in another process. Meaning every process will start and try to open the same port. Since the first process occupies the port, every other process will fail to spin up since the port is already taken/busy.

It might be best to work with a unique port for each process and use Nginx to load balance incoming requests and pass them to a running process. NODE_APP_INSTANCE is an ENV var you could use to create unique ports.

This article might get you there: https://medium.com/@samanbaboli/how-to-load-balancing-nodejs-apps-using-nginx-a3b4ceb7c782

muresanandrei commented 4 years ago

@happyDemon So something like this should work ?

Run laravel echo in 4 different ports: pm2 start server.js -f -- 6001 pm2 start server.js -f -- 6002 pm2 start server.js -f -- 6003 pm2 start server.js -f -- 6004

Then on nginx part:

upstream my_socketio_servers {
    server https://localhost:6001;      # httpsServer1 listens to port 6001
    server https://localhost:6002;     # httpsServer2 listens to port 6002
    server https://localhost:6003;      # httpsServer3 listens to port 6003
    server https://localhost:6004;     # httpsServer4 listens to port 6004
}

 location /socket.io {
    ip_hash;   //this directive is needed for socket.io or else it says it will fail
     proxy_pass https://my_socketio_servers;
     proxy_redirect off;
     proxy_http_version 1.1;
     proxy_set_header   X-Real-IP $remote_addr;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "Upgrade";
 }
SelimSalihovic commented 3 years ago

Any update on this? Did anyone manage to use multiple nodes for the same application?