How to configure load balancing using Nginx on Ubuntu Server 20.04

Louis SanchezJuly 29th 2021, 8:10

You will need a minimum of three servers, as follows:

An Nginx server, which will be set as a load balancer (example.com)

Two or more application servers with a similar code base set up on all (srv1.example.com, srv2.example.com, 192.168.1.1:8080...)

Step 1 : Install Nginx with the following command

sudo apt-get update
sudo apt-get install nginx

Step 2 : Now, create a new configuration file under /etc/nginx/sites-available. Let's call it load_balancer

sudo nano /etc/nginx/sites-available/load_balancer
upstream backend {
    server srv1.example.com:8081;
    server srv2.example.com:8082;
    server 192.168.1.1:8080;
    # other servers if any
}

server {
    listen 80;
    server_name example.com;
    location / {
        proxy_pass http://backend;
    }
}

Step 3 : Enable this configuration by creating a symlink to load_balancer under sites-enabled

sudo ln -s /etc/nginx/sites-available/load_balancer /etc/nginx/sites-enabled/load_balancer

Step 4 : Check the configuration

sudo nginx -t

Step 5 : Now, reload Nginx

sudo service nginx reload

Step 6 : Yes, you are ready to use a load balancer. Open your favorite browser and point it to the IP of your Nginx server. You should see the contents of example.com or whatever domain you have used