Nginx, loadbalancer and socket.io

I am trying to use a nginx server that connect’s to a load balancer that connects to a Socket.io service.
When running one service with Socket.IO it works fine, but as soon as I scale up the service to more than one it keeps connecting and disconnecting all the time.

To me it seems that the nginx server and the loadbalancer(in rancher) keeps changing the connection and therefore the socket service keeps connecting and disconnecting.

Anyone who had similar problems and actually got i working?

Here is the Nginx configuration

server {

  listen 8008; #http
  listen 8009; #https
  server_name testsocket.com;
  
  location / {
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_http_version 1.1;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_pass http://$http_host;
  }
}

upstream

upstream testsocket.com {
  ip_hash;
  server 213.179.54.30:4600;
  server 213.179.54.31:4600;
}

LoadBalancer
is connected to the service on port 4600

socket Service

    var express = require('express');
    var app = express();
    app.port = process.env.PORT || 4600;
    var redis = require('socket.io-redis');
    var socket_io = require('socket.io');
    var io = socket_io({adapter: redis({host: 'ADDRESSTOREDIS'})});
    io.on('connection', function (socket) {
            console.log('connected');
                    
            socket.on('disconnect', function() {
                console.log('socket disconnected');
            });
        });
app.io = io;


var server = app.listen(app.port,function () {
    app.io.attach(server);

});

Sounds like you need to configure some persistence (stickiness) somewhere. I don’t understand your configuration (mostly the Nginx part) enough to say where. Should be easy if it’s on the Rancher LB (HAProxy).

You’ll need to setup sticky sessions for the socket connections, within nginx.

Also, you should look into using something like socket.io-redis (https://github.com/socketio/socket.io-redis). This stores the sockets in Redis, so they’re available over the socket.io containers.