Now that we understand the power of Nginx as a reverse proxy, let's dive into one of its most crucial features: load balancing. Load balancing is the technique of distributing incoming network traffic across multiple backend servers. This not only improves application responsiveness and increases throughput but also enhances reliability by ensuring that if one server fails, traffic can be seamlessly rerouted to the remaining healthy servers.
Nginx offers several built-in load balancing methods, each with its own strengths and ideal use cases. We'll explore the most common ones and demonstrate how to configure them.
This is the simplest and most common load balancing algorithm. In Round Robin, Nginx distributes incoming requests to the backend servers in a sequential, rotating manner. Each server receives an equal number of requests.
http {
upstream backend_servers {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend_servers;
}
}
}In this configuration, requests will be sent to backend1.example.com, then backend2.example.com, then backend3.example.com, and then cycle back to backend1.example.com.
graph LR;
Client --> Nginx;
Nginx -- Request 1 --> Server1;
Nginx -- Request 2 --> Server2;
Nginx -- Request 3 --> Server3;
Nginx -- Request 4 --> Server1;
Sometimes, your backend servers might have different capacities or performance levels. Weighted Round Robin allows you to assign a 'weight' to each server. Servers with higher weights will receive a proportionally larger share of the traffic.