How NGINX Load Balancing Works
The basic principle of a Load Balancer is that it sits between the user and a set of servers, and proxies requests for them. Usually this is done with two or more servers, so that traffic can be distributed more easily between them.
Most of the configuration happens in how NGINX selects which server to route to. The default is round-robin, which will send requests to each server in order, ensuring an equal load distribution.
However, it’s not always that simple. Many web applications require some form of session persistence, which means that the user must be accessing the same server for their whole session. For example, a shopping cart might be stored locally on one application server, and if the user switches servers mid-session, the application could glitch out. Of course, many of these scenarios can be fixed with better application infrastructure and centralized datastores, but session persistence is required by many people.
In NGINX, the set of servers that you route to is known as an upstream, and is configured like an enumerated list of addresses:
These upstreams have a lot of options; here, we’ve set a weight, which will prioritize this server more often (particularly useful if you have different sizes). You can also set the max connnections and various timeouts. If you’re using NGINX Plus, you can also set up health checks so that connections don’t get routed to unhealthy servers.
The most basic form of session persistence is using an IP hash. NGINX will use the IP to identify users and then make sure that these users don’t switch servers mid-session:
The IP hash is required for socket-based applications and anything requiring persistence. If you don’t want to use the IP address, you can customize this hash:
If you don’t need any kind of session persistence, you can make the round-robin selection a little smarter by selecting which server has the least connections:
Or, based on which one is currently responding fastest:
NGINX Plus has a few other forms of session persistence, but IP hashing will work for most applications.
Proxying to the Backend
Once you’ve got your backend configured, you can send requests to it from within your location blocks, using proxy_pass with a URI to the backend.
Of course, if you’re using HTTPS, you’ll need to send the request with HTTPS: