0
0
NginxHow-ToBeginner · 4 min read

How to Use IP Hash Load Balancing in NGINX

To use ip_hash load balancing in NGINX, add the ip_hash; directive inside the upstream block. This makes NGINX route requests from the same client IP to the same backend server, ensuring session persistence.
📐

Syntax

The ip_hash directive is placed inside an upstream block to enable load balancing based on client IP addresses.

Each part explained:

  • upstream backend { ... }: Defines a group of backend servers.
  • ip_hash;: Enables IP hash load balancing.
  • server IP:port;: Lists backend servers to receive traffic.
nginx
upstream backend {
    ip_hash;
    server 192.168.1.10:80;
    server 192.168.1.11:80;
}
💻

Example

This example shows a full NGINX configuration using ip_hash to balance requests between two backend servers. Requests from the same client IP always go to the same server.

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

    server {
        listen 80;

        location / {
            proxy_pass http://backend;
        }
    }
}
Output
NGINX starts successfully and routes client requests so that each client IP consistently reaches the same backend server.
⚠️

Common Pitfalls

Common mistakes when using ip_hash include:

  • Placing ip_hash outside the upstream block, which causes errors.
  • Using ip_hash with least_conn or other load balancing methods simultaneously, which is not allowed.
  • Not listing backend servers correctly, causing uneven load or failures.

Always ensure ip_hash is the only load balancing method in the upstream block.

nginx
upstream backend {
    # Wrong: mixing ip_hash with least_conn
    ip_hash;
    least_conn;
    server 192.168.1.10:80;
    server 192.168.1.11:80;
}

# Correct usage:
upstream backend {
    ip_hash;
    server 192.168.1.10:80;
    server 192.168.1.11:80;
}
📊

Quick Reference

DirectiveDescription
ip_hash;Enables IP hash load balancing inside an upstream block
upstream name { ... }Defines backend server group
server IP:port;Specifies a backend server
proxy_pass http://name;Sends client requests to the upstream group

Key Takeaways

Use ip_hash; inside the upstream block to enable IP-based load balancing.
IP hash ensures clients with the same IP reach the same backend server for session persistence.
Do not mix ip_hash with other load balancing methods like least_conn.
List all backend servers correctly inside the upstream block.
Configure proxy_pass to point to the upstream group to apply load balancing.