Howtos / Articles

Load Balancing with Nginx

Nginx is a high performance web server, which can also act as a great reverse proxy. Reverse proxy’s are placed in front of the web server handling the processing, to speed the site up, by either caching data, and/or load balancing across multiple back-end web servers.

This howto will outline the steps required to set up Nginx as a load balancing reverse proxy.

Simple round robin load balancer configuration

This is the simpilest method of load balancing. It will simply cycle through the backends using a round robin method. The weight option can be used to give priority to allow more traffic to a specific backend. This can be usefull if one of the servers is more powerful than the others. The example below will send 3 times more traffic to the first backend compared with the other 3 backend servers.

http {
  upstream backendservers {
    server 192.168.0.11:80 weight=3;
    server 192.168.0.12:80;
    server 192.168.0.13:80;    
    server 192.168.0.14:80;
  }
 
  server {
    listen 80;
    server_name www.yourdomain.com;
    location / {
      proxy_pass http://backendservers;
    }
  }
}

Round robin load balancing based on source ip hash

This sample configuration allows you to redirect users back to the same backend server on their next connection. This is helpfull to maintain session state on a specific backend server.

http {
  upstream backendservers {
    ip_hash;
    server 192.168.0.11:80 weight=3;
    server 192.168.0.12:80;
    server 192.168.0.13:80;    
    server 192.168.0.14:80;
  }
 
  server {
    listen 80;
    server_name www.yourdomain.com;
    location / {
      proxy_pass http://backendservers;
    }
  }
}

Load balancing to servers with the least number of connections

This will direct traffic to one of the back end servers that has the least number of concurrent connections at the time the request was made.

http {
  upstream backendservers {
    least_conn;
    server 192.168.0.11:80;
    server 192.168.0.12:80;
    server 192.168.0.13:80;    
    server 192.168.0.14:80;
  }
 
  server {
    listen 80;
    server_name www.yourdomain.com;
    location / {
      proxy_pass http://backendservers;
    }
  }
}

For more information on using the Upstream module Nginx, you can visit http://wiki.nginx.org/HttpUpstreamModule



Share this howto article!
  • Facebook
  • Twitter
  • Reddit
  • email

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>