2020年 · 点滴记录

nginx负载均衡upstream ip_hash的用法

负载均衡解决session共享的问题

参考文档:https://nginx.org/en/docs/http/ngx_http_upstream_module.html

Syntax: ip_hash;
Default:
Context: upstream

Specifies that a group should use a load balancing method where requests are distributed between servers based on client IP addresses. The first three octets of the client IPv4 address, or the entire IPv6 address, are used as a hashing key. The method ensures that requests from the same client will always be passed to the same server except when this server is unavailable. In the latter case client requests will be passed to another server. Most probably, it will always be the same server as well.

ip_hash可以依据请求来源IP对真实服务器的分配。取ipv4类型Ip的前三位字节 或者ipv6的整个ip作为hashing key, 这个方法可以确保访问一个被同一台服务器处理, 除非分配的server宕机。 如果宕机 则请求被发往其他的机器。

If one of the servers needs to be temporarily removed, it should be marked with the down parameter in order to preserve the current hashing of client IP addresses.

如果其中的一个server需要临时删除, 则应该使用down对其进行标记,以保留当前客户端IP地址的hashing key

例如:

upstream backend {
    ip_hash;

    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com down;
    server backend4.example.com;
}