Load Balancing 2 Nginx Servers with another NginxServer as Reverse-Proxy

This is a POC project.

Set-ups

  • Total 3 Nginx servers running as docker containers
docker run -d -p 8071:80 --name LB nginx
docker run -d -p 8072:80 --name S1 nginx
docker run -d -p 8073:80 --name S2 nginx
  • One server used as Load-Balancer "LB"

    Two servers used as web-servers "S1" & "S2"

  • Get the Nginx Server IPs

Here's the server IPs for Server-1 S1 & Server-2 S2

172.17.0.3
172.17.0.4

Nginx as Load Balancer --> LB

  • Modify the Nginx config file
upstream web_backend {
    server 172.17.0.3;
    server 172.17.0.4;
}
server {
    listen 80;
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://web_backend;
    }
}
  • Copy the above config contents to Nginx config within LB docker container

/etc/nginx/conf.d/default.conf


Nginx as Web-Servers --> S1 & S2

  • Now we need to add some HTML content that will be served by S1 & S2 (must be different so we can distinguish which server served the request just by looking at the HTML content itself).

  • Add the index.html content to Web Server S1 docker container - /usr/share/nginx/html/index.html

This is the html content that will be served by Web Server S1 to prove that the request is processed by Web Server S1 or Server1

<p> 
----------------------------------

    Page served by Server-1

----------------------------------
</p>
  • Add the index.html content to Web Server S2 docker container - /usr/share/nginx/html/index.html

This is the html content that will be served by Web Server S2 to prove that the request is processed by Web Server S2 or Server2

<p> 
----------------------------------

    Page served by Server-2

----------------------------------
</p>

Testing

  • Restart all the docker containers - i.e. Load Balancer LB, Web Server S1 & S2 - after all the files are copied.
docker restart LB S1 S2
  • Check the content served through LB port 80 (do you remember we mapped it to 8071 ?)

So curl localhost:80

becomes

curl localhost:8071

  • Everytime you run the above, you get "different content value" (i.e. Server S1 or S2) - which justifies the fact that traffic is "load-balanced" to different server - hence "different content value".