Low Orbit Flux Logo 2

NGINX Load Balancing

nginx web server logo

Setting up a load balancer with NGINX is easy. Really simple load balancing configuration. Just add this to your server block. This will use round-robin to balance connections by default.


sudo vi /etc/nginx/sites-available/default

http {
    upstream example.org {
        server web1.example.com;
        server web2.example.com;
        server web3.example.com;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://example.org;
        }
    }
}

Thats it! You’re done!

Keep reading if you want to learn more.

Setting up a load balancer or reverse proxy gives you the following:

Load balancing alorithms to choose from:

NGINX can load balance these things:

Least Connected

If you want to use least connected instead of round robin you can use the ‘least_conn’ directive as shown in the example below. Just change one line.


http {
    upstream example.org {
        least_conn;
        server web1.example.com;
        server web2.example.com;
        server web3.example.com;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://example.org;
        }
    }
}

Weighted Load Balancing

If you want to give more weight to a given server you can. For example, out of 10 connections, web1 will receive 6 connections while web2 and web3 will only receive 2 connections each.


    upstream myapp1 {
        server web1.example.com weight=3;
        server web2.example.com;
        server web3.example.com;
    }

Weighted load balancing also works with least-connected and ip-hash in newer versions of NGINX.

More

There is a lot more to know. You can check the “further reading” section on this page:

HERE.