Configuring DNS for nginx and confirming load balancing.

April 23, 2018 1.5k views
Nginx Ubuntu

Hi, I'm testing out nginx round-robin load balancing and am fairly new to this.

1)Can I configure DNS so that I can access the webserver via a domain name instead of IP?
2)How can I check if load balancing is working? I have 2 web servers and want to know which server gets the request when a client sends the request.

This is my nginx code(very basic)

    upstream web_backend {
    server 10.11.12.51;
    server 10.11.12.52;
    }

    server {
    listen 80;


    location / {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_pass http://web_backend;
    }
}
1 Answer

To bind domain(s) to your server block you need to add the server_name directive. Below is an updated config.

Adding least_conn; in your upstream block allows for NGINX to more fairly distribute the load across your upstream server(s). More information on the different algorithms can be found here -- http://nginx.org/en/docs/http/load_balancing.html --

The first server block redirects the non-www version of the domain to the www version.

The second block handles the www request and passes that onto your upstream server(s).

upstream web_backend {
    least_conn;
    server 10.11.12.51;
    server 10.11.12.52;
}

server {
    listen 80;

    server_name yourdomain.com;

    location / {
        return 301 http://www.$server_name$requrst_uri;
    }
}

server {
    listen 80;

    server_name www.yourdomain.com;

    location / {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_pass http://web_backend;
    }
}
Have another answer? Share your knowledge.