Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Patching Nginx to ip_hash 4 octets instead of 3

I'm currently running two back end servers on my network and load balancing with Nginx on Windows.

I am load testing the system at the moment however all of my traffic is directed at one server. This is because the ip_hash algorithm sorts traffics by the first 3 octets i.e. 111.222.333.XXX

This is a problem because all of the traffic I am aiming at the server has the same base address (The same first 3 octets) therefore none of my traffic is going to the other server. Does anyone know a way to patch or change the ip_hash algorithm to filter through 4 octets.

Thanks

like image 323
Sprout Avatar asked Sep 08 '15 14:09

Sprout


People also ask

Does nginx support sticky session?

NGINX natively manages session persistence in several ways, including using cookies and sticky routes.

Can Nginx do load balancing?

It is possible to use nginx as a very efficient HTTP load balancer to distribute traffic to several application servers and to improve performance, scalability and reliability of web applications with nginx.

How do I know if nginx load balancing is working?

To test the Nginx load balancing, open a web browser and use the following address to navigate. Once the website interface loads, take note of the application instance that has loaded. Then continuously refresh the page. At some point, the app should be loaded from the second server indicating load balancing.


1 Answers

Nginx open source version supports the hash directive that may work similarly (not exactly the same though) to the sticky session mechanism provided by commercial version:

The generic hash method: the server to which a request is sent is determined from a user-defined key which may be a text, variable, or their combination. For example, the key may be a source IP and port, or URI:

upstream backend {
    hash $request_uri consistent;

    server backend1.example.com;
    server backend2.example.com;
}

https://www.nginx.com/resources/admin-guide/load-balancer/

So how do you use 4 octets from IPv4 with the hash method? Let's find how to get the client IP from the Embedded Variables section http://nginx.org/en/docs/http/ngx_http_core_module.html#variables

$remote_addr client address

So the code looks like:

upstream backend {
    hash $remote_addr consistent;

    server backend1.example.com;
    server backend2.example.com;
}

UPDATE:

If take a look at the Stream module (TCP proxy), the very first example shows exact the same approach:

upstream backend {
    hash $remote_addr consistent;

    server backend1.example.com:12345  weight=5;
    server backend2.example.com:12345;
    server unix:/tmp/backend3;
}

server {
    listen 12346;
    proxy_pass backend;
}
like image 174
Anatoly Avatar answered Oct 15 '22 21:10

Anatoly