I have a chat application using socket.io. I put code on 2 server (ip1, ip2) and using nginx to make load balancing.
this is nginx config
upstream socket_nodes {
ip_hash;
server ip1:1654;
server ip2:1653;
}
server {
listen 1653;
server_name livechatsoftware.com.vn;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-NginX-Proxy true;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_pass http://socket_nodes;
proxy_redirect off;
}
}
Everything is working well if clients connect to same server. but if client 1 connect to server ip1, client 2 connect to server ip2. client 1 and client 2 can not interact (eg cannot emit, send message,....)
Thanks for advance
I am using nginx to load balance my node processes (express.js + mongodb + socket.io + passport.js) . Although they are all in the same server, still socket.io events don't get shared between them. That means I've also faced the exact same issue. So I've used mong.socket.io (https://github.com/tmfkmoney/mong.socket.io) to store socket.io events in the mongo store. In that way each socket.io process reads the events from a centralized store.
You also need a central store which socket.io events can be accessed from any of the servers. I've never used that kind of setup but check out the below package;
https://www.npmjs.com/package/socket.io-redis
I'd install redis to one of my servers and point my socket.io processes to that server like below;
io.adapter(redis({ host: 'localhost', port: 6379 })); // you should use ip address and the port for the remote server
You can also use other adapter options as mentioned in the past link I've shared.