About Me

My photo
I know the last digit of PI

Thursday, June 30, 2016

NGINX Reverse proxy and load balancer for Java servers

This is a simple script for the load balancing and reverse proxy configuration for an application called "myAppName" which runs on two servers "https://xxxxx:8080/myAppName" and "https://yyyyy:8080/myAppName". The script is designed for Java servers (tomcat, glassfish, jboss, etc.)

However please note that since NGINX open source doesn't support sticky it is not suitable for productive environments load balancing, because it uses ip_hash directive, which tells nginx that all request from particular IP to be served by one and the same server. If that IP is the external IP of large internal LAN (via NAT), then it means only one server will be loaded, which may crash that server. If you are not willing to pay $1900/yr then stick to apache httpd.

There are two options - the reverse proxy machine is serving all requests on the root "/" or "/myAppName".

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;
    
    # Load balancing    
    upstream myAppName {        
        ip_hash;
        server xxxxx:8080;
        server yyyyy:8081;
    }
    
    server {
        listen       1080;
        server_name  localhost;

        location / {
            rewrite ^/myAppName/(.*)$  /myAppName/$1 break;
            rewrite ^(.*)$  /myAppName/$1 break;
            proxy_pass http://myAppName;
            proxy_cookie_path / /myAppName;    
        }
        
        #location /myAppName {            
        #    proxy_pass http://myAppName;
        #    proxy_cookie_path /myAppName/ /myAppName;    
        #    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        #    proxy_set_header Host $http_host;
        #    proxy_set_header X-Real-IP $remote_addr;
        #    proxy_set_header X-Forwarded-Proto https;
        #    proxy_redirect off;
        #    proxy_connect_timeout      240;
        #    proxy_send_timeout         240;
        #    proxy_read_timeout         240;
        #    if ($http_cookie ~* "jsessionid=([^;]+)(?:;|$)") {
        #        set $co "jsessionid=$1";
        #    }
        #    proxy_set_header Cookie "$co";            
        #}
    }    
}