Nginx配置说明

2017-06-18  本文已影响459人  乐楽樂

upstream 配置

upstream backend{
    server 192.168.1.11:8080 weight=1;
    server 192.168.1.12:8080 weight=2;
}
location / {
    proxy_pass http://backend;
}

负载均衡算法

负载均衡用来解决用户请求到来时如何选择upstream server,默认采用轮询round-robin

upstream backend{
    ip_hash;
    server 192.168.1.11:8080 weight=1;
    server 192.168.1.12:8080 weight=2;
}
哈希算法
upstream backend{
    hash $uri 
    server 192.168.1.11:8080 weight=1;
    server 192.168.1.12:8080 weight=2;
}
哈希一致性算法
upstream backend{
    hash $consistent_key consistent;
    server 192.168.1.11:8080 weight=1;
    server 192.168.1.12:8080 weight=2;
}

失败重试

通过配置max_fails和max_timeout来指定每个上游服务器失败次数

upstream backend {
    server 192.168.1.11:8080 max_fails=2 fail_timeout=10s weight=1;
    server 192.168.1.12:8080 max_fails=2 fail_timeout=10s weight=1;
}

location /{
    proxy_connect_timeout 5s;
    proxy_read_timeout 5s;
    proxy_timeout 5s;
    
    proxy_next_upstream error timeout;
    proxy_next_upstream_timeout 10s;
    proxy_next_upstream_tries 2;
    proxy_pass http://backend;
    add_header upstream_add $upstream_add;
}

TCP心跳检查

upstream backend{
    server 192.168.1.11:8080 weight=1;
    server 192.168.1.12:8080 weight=2;
    check interval=3000 rise=1 fall=3 timeout=2000 type=tcp;
}

HTTP心跳检查

upstream backend{
    server 192.168.1.11:8080 weight=1;
    server 192.168.1.12:8080 weight=2;
    
    check interval=3000 rise=1 fall=3 timeout=2000 type=http;
    check_http_send "HEAD /status HTTP/1.0\r\n\r\n";
    check_http_expect_alive http_2xx http_3xx;
}

注意:检查时间间隔不能太短,否则可能因为心跳检查包太多导致服务器挂掉
本文使用的是openresty/1.11.2.1(对应nginx-1.11.2),安装之前需要打nginx_upstream_check_module补丁(check_1.9.2+.patch)到Nginx目录下执行shell:

patch -p0</usr/servers/nginx_upstream_check_module-master/check_1.9.2+.patch

如果不安装补丁,那么ngixn_upstream_check_module模块是不工作的,建议使用wireshark抓包查看是否工作.

上一篇 下一篇

猜你喜欢

热点阅读