node.jsnginxload-balancing

Load balancing with nginx using hash method


I want to use nginx as a load balancer in front of several node.js application nodes.

round-robin and ip_hash methods are unbelievably easy to implement but in my use case, they're not the best fit.

I need nginx to serve clients to backend nodes in respect to their session id's which are given by first-landed node.

During my googlings, I've come up with "hash"ing method but I couldn't find too many resources around.

Here is what I tried:

my_site.conf:

http {

    upstream my_servers {
        hash $remote_addr$http_session_id consistent;
        server 127.0.0.1:3000;
        server 127.0.0.1:3001;
        server 127.0.0.1:3002;
    }

    server {
        listen 1234;
        server_name example.com;

        location / {
            proxy_pass http://my_servers;
            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
            proxy_redirect off;
            proxy_buffering off;
            proxy_set_header        X-Real-IP       $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

And at the application, I return Session-ID header with the session id.

res.setHeader('Session-ID', req.sessionID);

I'm missing something, but what?


Solution

  • $http_session_id refers to header sent by client (browser), not your application response. And what you need is http://nginx.org/r/sticky, but it's in commercial subscription only.

    There is third-party module that will do the same as commercial one, but you'll have to recompile nginx.