Load balancing a commonly used technique for optimizing resource utilization, maximizing throughput, reducing latency, and ensuring fault‑tolerant configurations. It involves distributing client requests across multiple servers to ensure no single server becomes a bottleneck.
To set up load balancing in Nginx, you’ll need to configure it in the nginx.conf
file or within a specific server block. The configuration involves defining an upstream block and specifying how requests should be distributed.
http {
upstream myapp {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
listen 80;
location / {
proxy_pass http://myapp;
}
}
}
In this example:
upstream
block defines a group of backend servers (backend1
, backend2
, backend3
).proxy_pass
directive in the location
block forwards requests to the upstream group.Nginx supports several load balancing algorithms. You can configure these methods using the upstream
directive.
upstream myapp {
server backend1.example.com;
server backend2.example.com;
}
upstream myapp {
least_conn;
server backend1.example.com;
server backend2.example.com;
}
upstream myapp {
ip_hash;
server backend1.example.com;
server backend2.example.com;
}
You can use Nginx to terminate SSL/TLS connections and then perform load balancing over HTTP. This setup involves configuring SSL/TLS in the server
block and proxying requests to the backend servers.
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://myapp;
}
}
nginx -t
to test configuration syntax before applying changes.