Load Balancing with Nginx: A Step-by-Step Implementation Guide
Load balancing distributes incoming traffic across multiple backend servers, improving reliability and scalability. Nginx makes this easy with its built‑in upstream module. This tutorial walks through a basic setup so you can balance HTTP traffic in minutes.
We assume you have Nginx installed on a Linux server and at least two backend servers (e.g., Node.js, Python, or static web servers) running on different ports or IPs. If not, install Nginx with sudo apt install nginx (Debian/Ubuntu) or equivalent. Now let’s configure the load balancer.
1. Define an Upstream Block
Open your Nginx config file (usually /etc/nginx/nginx.conf or a site file in sites-available). Inside the http block, add an upstream section listing your backend servers:
upstream backend {
server backend1.example.com weight=3;
server backend2.example.com;
server 192.168.1.101:3000;
}
Use IPs or domain names; add optional weight to assign more traffic to powerful servers.
2. Configure a Proxy Pass
Create or modify a server block that listens on port 80 (or 443 for HTTPS). Within a location / block, pass requests to the upstream group:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
The proxy_pass directive forwards all requests to the backend upstream. The header lines preserve original client information.
3. Choose a Load Balancing Method
Nginx supports several algorithms. Add one to the upstream block:
- round-robin (default): distributes requests evenly in order.
- least_conn: sends new requests to the server with the fewest active connections.
- ip_hash: ensures a client always hits the same backend (useful for session persistence).
Example with least_conn:
upstream backend {
least_conn;
server backend1.example.com;
server backend2.example.com;
}
4. Finalize and Test
Save the config and check for syntax errors: sudo nginx -t. Then reload Nginx: sudo systemctl reload nginx or sudo nginx -s reload. Visit your domain and observe traffic evenly distributed among your backends.
Load balancing with Nginx is lightweight and production‑ready. Start with round‑robin, monitor performance, and tweak weights or methods as your traffic grows. For HTTPS, add SSL certificates via Certbot—the same upstream configuration works seamlessly.