Sticky Session Load Balancer with Nginx
Load balancer distributes incoming requests across multiple computing application servers. It aims to optimize resource use, maximize throughput, minimize response time, and avoid overload of any single resource.
Nginx supports below load balancing mechanisms:
- Round-Robin — Requests to the application servers are distributed in a round-robin fashion.
- Least-Connected — Next request is assigned to the server with the least number of active connections.
- Ip-Hash — A hash-function is used to determine what server should be selected for the next request (based on the client’s IP address).
In this post, we will learn how to configure Ip-Hash Load Balancing with Nginx, following below steps:
Step 1: Download Nginx from here.
Step 2: Unzip the nginx-*.tar.gz and install the it using command:
$ cd nginx-1.9.6 $ ./configure $ make $ make install
By default, Nginx will be installed in directory /usr/local/nginx, but Nginx provides the ability to specify a directory where it is to be installed, and same you can do it by providing additional compile option – –prefix as follows:
./configure --prefix=/Users/ArpitAggarwal
For all available compile options use below command:
./configure --help
Step 3: Start any number of tomcat instances which are a part of a cluster, for me it’s 3 running on a localhost on port 8080, 8081, 8082 and define upstream block in /usr/local/nginx/conf/nginx.conf file, as follows:
upstream cluster-tomcat { server 127.0.0.1:8080; server 127.0.0.1:8081; server 127.0.0.1:8082; }
Above all requests are proxied to the server group cluster-tomcat in a round-robin fashion and Nginx applies HTTP load balancing to distribute the requests.
Step 4: Replace location block under server with below:
location / { proxy_pass http://cluster-tomcat; }
Step 5: Enable Sticky Session adding ip_hash directive to the server (upstream) group configuration, as follows:
upstream cluster-tomcat { ip_hash; server 127.0.0.1:8080; server 127.0.0.1:8081; server 127.0.0.1:8082; }
After making changes, complete http block should look like:
http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream cluster-tomcat { ip_hash; server 127.0.0.1:8080; server 127.0.0.1:8081; server 127.0.0.1:8082; } server { listen 80; server_name localhost; location / { proxy_pass http://cluster-tomcat; } } }
Reference: | Sticky Session Load Balancer with Nginx from our SCG partner Arpit Aggarwal at the Arpit Aggarwal blog. |