How to Configure Load Balancer with NGINX: Simple Guide
To configure a load balancer in
nginx, define an upstream block listing backend servers and use the proxy_pass directive in a server block to forward requests. This setup distributes incoming traffic evenly across multiple servers.Syntax
The basic syntax for configuring load balancing in nginx involves two main parts:
- upstream block: Defines a group of backend servers to balance the load.
- server block: Uses
proxy_passto forward client requests to the upstream group.
Each backend server is listed with its IP or hostname and optional parameters like weight or max_fails.
nginx
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}Example
This example shows a simple load balancer setup where nginx listens on port 80 and distributes requests to two backend servers named backend1.example.com and backend2.example.com.
nginx
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}Output
When a client sends a request to the NGINX server on port 80, the request is forwarded to either backend1.example.com or backend2.example.com in a round-robin fashion by default.
Common Pitfalls
Common mistakes when configuring NGINX load balancer include:
- Not defining the
upstreamblock before referencing it inproxy_pass. - Forgetting to set necessary proxy headers like
HostandX-Real-IP, which can cause backend servers to misinterpret requests. - Using IP addresses without proper DNS or network setup, causing connection failures.
- Not testing backend server health, which can lead to forwarding requests to down servers.
nginx
## Wrong: Missing upstream block
server {
listen 80;
location / {
proxy_pass http://backend;
}
}
## Right: Define upstream block
upstream backend {
server 192.168.1.10;
server 192.168.1.11;
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}Quick Reference
Key points to remember when configuring NGINX load balancer:
- upstream block: Lists backend servers.
- proxy_pass: Forwards requests to upstream group.
- proxy_set_header: Passes client info to backend.
- Load balancing methods: Round-robin (default), least_conn, ip_hash.
- Health checks: Use third-party modules or external tools to monitor backend health.
Key Takeaways
Define backend servers in an upstream block to enable load balancing.
Use proxy_pass in a server block to forward client requests to the upstream group.
Set proxy headers to preserve client information for backend servers.
Test your configuration and backend server availability to avoid downtime.
Choose appropriate load balancing methods based on your traffic needs.