0
0
NginxHow-ToBeginner · 4 min read

How to Use Least Connections Load Balancing in NGINX

To use least_conn load balancing in NGINX, set the least_conn directive inside the upstream block. This tells NGINX to send new requests to the server with the fewest active connections, balancing load more evenly.
📐

Syntax

The least_conn directive is used inside an upstream block to enable least connections load balancing. It tells NGINX to pick the server with the fewest active connections for each new request.

Example parts:

  • upstream backend { ... }: Defines a group of servers.
  • least_conn;: Enables least connections load balancing.
  • server IP:port;: Lists backend servers.
nginx
upstream backend {
    least_conn;
    server 192.168.1.10:80;
    server 192.168.1.11:80;
    server 192.168.1.12:80;
}
💻

Example

This example shows a simple NGINX configuration using least connections load balancing to distribute requests among three backend servers.

nginx
http {
    upstream backend {
        least_conn;
        server 192.168.1.10:80;
        server 192.168.1.11:80;
        server 192.168.1.12:80;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://backend;
        }
    }
}
Output
NGINX starts and balances incoming requests to the backend servers by sending each new request to the server with the fewest active connections.
⚠️

Common Pitfalls

Common mistakes when using least_conn include:

  • Not defining the least_conn; directive inside the upstream block, which defaults to round-robin.
  • Mixing least_conn with other load balancing methods in the same block, which is not allowed.
  • Not properly listing backend servers or using incorrect IPs/ports.
  • Forgetting to reload or restart NGINX after configuration changes.
nginx
upstream backend {
    # Wrong: mixing methods
    least_conn;
    ip_hash;
    server 192.168.1.10:80;
    server 192.168.1.11:80;
}

# Correct way:
upstream backend {
    least_conn;
    server 192.168.1.10:80;
    server 192.168.1.11:80;
}
📊

Quick Reference

DirectiveDescription
least_conn;Enables least connections load balancing in an upstream block.
server IP:port;Defines a backend server to receive traffic.
proxy_pass http://backend;Sends client requests to the upstream group named 'backend'.

Key Takeaways

Use the least_conn directive inside an upstream block to enable least connections load balancing.
NGINX sends new requests to the server with the fewest active connections for better load distribution.
Do not mix least_conn with other load balancing methods like ip_hash in the same upstream block.
Always reload or restart NGINX after changing the load balancing configuration.
Verify backend server IPs and ports are correct to avoid connection errors.