Nginx – Single Nginx Load Balancer for 2 different clusters (web, api)

high-availabilityload balancingnginx

I was wondering if it was possible to use a single Nginx server to load balance my web servers and api servers if both are using port 80. In this setup there would be 5 servers, 1 Nginx and 4 Apache servers. I would like the web servers to be balanced when web.example.com is accessed. Likewise, I would like the api servers to be balanced when api.example.com is accessed.

Is this possible or do I need another nginx server?

Best Answer

You have two possible approach :

1. A single VIP for both farms :

In this case, your VIP will be your NGinx server single ip address.

http {
  upstream web.example.com {
    least_conn;
    server mywebserver1.loc;
    server mywebserver2.loc;
    server mywebserver3.loc;
  }

  upstream api.example.com {
    least_conn;
    server myapiserver1.loc;
    server myapiserver2.loc;
    server myapiserver3.loc;
  }

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

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

  }

2. A dedicated VIP for each farms

In that case you need two IP Address on the NGinx host.

Let's say :

  • 192.168.1.1 for Web (eth0)
  • 192.168.1.2 for Api (eth1)

    http {
      upstream web.example.com {
      least_conn;
      server mywebserver1.loc;
      server mywebserver2.loc;
      server mywebserver3.loc;
    }
    
    upstream api.example.com {
      least_conn;
      server myapiserver1.loc;
      server myapiserver2.loc;
      server myapiserver3.loc;
    }
    
    server {
      listen 192.168.1.1:80;   # <-- vHost listen on IP
      server_name web.example.com;
      location / {
        proxy_pass http://web.example.com
      }
    
     server {
      listen 192.168.1.2:80;   # <-- vHost listen on IP
      server_name api.example.com;
      location / {
        proxy_pass http://api.example.com
      }
    
    }
    

Then you have multiple options to manage load-balancing and failover in upstream directive, like :

  • weight
  • max_fails
  • fail_timeout

http://wiki.nginx.org/NginxHttpUpstreamModule#upstream

Also, you have multiple load-balancing method :

  • least-connected
  • Session persistence

http://nginx.org/en/docs/http/load_balancing.html

Related Topic