hash
The 'hash' directive sets the hash algorithm used for distributing requests to upstream servers in NGINX.
Description
The 'hash' directive is used within the 'upstream' context to define a hash algorithm for distributing client requests to the defined upstream servers. This mechanism allows NGINX to manage load balancing across multiple backend services based on the hash of the key, which typically is an IP address or other specified data.
The directive can take one or two arguments. The first argument is the key that gets hashed, and the optional second argument allows specifying a specific algorithm (like 'consistent'). The default behavior uses a simple hash algorithm, but specifying one can provide deterministic results that improve session persistence.
When utilizing the 'hash' directive, various factors, such as the number of upstream servers and session affinity requirements, should be considered for optimal performance. The directive ensures that requests from the same client (based on the hash key) are consistently sent to the same upstream server, which is especially beneficial for stateful applications that rely on session data being stored locally on a specific server.
Config Example
upstream backend {
hash $remote_addr;
server backend1.example.com;
server backend2.example.com;
}When using a non-default hash algorithm, ensure compatibility with your upstream server configurations.
Misconfigurations in session persistence can lead to uneven load distribution or increased latency.
Remember to review client key selection to prevent hash collisions which can adversely affect load balancing behavior.