Nginx负载均衡与反向代理

来源:互联网 发布:雅思听力选择题 知乎 编辑:程序博客网 时间:2024/06/07 13:55

上游服务器配置

在http指令下配置:

upstream backend {    ip_hash;    // 负载均衡算法    server 192.168.61.1:8080  weight=1;    server 192.168.61.1:8080  weight=2;  // 权重越高流量越大}

使用proxy_pass处理用户请求

location / {    proxy_pass http://backend}

负载均衡算法

  • round-robin ( 默认)
  • ip_hash :根据IP映射
  • hash key [consistent] : 建议使用一致性hash,当添加/删除服务器时,只有少数key被重新负载均衡到不同服务区,如:
hash $consistent_key consistent; // $consistent_key 可动态指定location / {    set $consistent_key $arg_cat;  // 先使用请求参数cat    if( $consistent_key = "" ) {        set $consistent_key $request_uri; // uri    }}

可通过lua设置一致性hash

set_by_lua_file $consistent_key "lua_balancing.lua"

lua_balancing.lua

local consistent_key = args.catif not consistent_key or consistent_key == '' then   consistent_key = ngx_var.request_uriendlocal value = balancing_cache:get(consistent_key)if not value then    success, err = balancing_cache:set(consistent_key, 1, 60 )else    newval, err = balancing_cache:incr(consistent_key, 1)   if newval > 5000 then  //        consistent_key = consistent_key .. '_' .. newval   endend

失败重试机制

upstream backend {  // 10秒中失败两次,即为不可用, 10秒后重试    server 192.168.1.1:8080 max_fails=2 fail_timeout=10s weight=1;}
location / {    proxy_connect_timeout 5s;    proxy_read_timeout 5s;    proxy_send_timeout 5s;    proxy_next_upstream error timeout;    proxy_next_upstream_timeout 10s;    proxy_next_upstream_tries 2;    proxy_pass http://backend}

服务器心跳检查

Nginx对上游服务器的健康检查默认采用惰性策略,也可以集成 nginx_upstream_check_module 进行主动检查

upstream backend {    server 192.168.1.1:8080 weight=1;    check interval=3000 rise=1 fall=3 timeout=2000 type=tcp;}
  • interval 间隔时间
  • fall 失败多少次后标记为不可用
  • rise 成功多少次后标记为可用
  • timeout 检测超时时间
http心跳检查
upstream backend {    //  ...    check_http_send "HEAD /status HTTP/1.0\r\n\r\n";    check_http_expect_alive http_2xx http_3xx;}

域名上游服务器

注意:IP地址发生变化时,upstream不会自动更新(商业版才支持),但是proxy_pass是支持动态解析的

备份和不可用

upstream backend {    server 192.168.1.1:8080 weight=1 backup;    server 192.168.1.1:8080 weight=1 down;}

长连接

nginx与上游服务器的长连接

upstream backend {    keepalive 100; //每个workder进程与上游服务器可缓存的控线连接的最大数量,超出后,最近最少使用的连接将被关闭。keepalive指令不限制worker进程与上游服务器的总连接}
location / {    # 支持keep-alive所需配置    proxy_http_version 1.1;    proxy_set_header Connection "";    proxy_pass http://backend;}

总长连接数 = 空闲连接池 + 释放连接池

反向代理

反向代理除了实现负载均衡外,还能提供缓存以减少上游服务器的压力
1. 全局配置(proxy cache )

proxy_buffering             on;proxy_buffer_size           4k;proxy_buffers               512 4k;proxy_busy_buffers_size     64k;proxy_temp_file_write_size  246k;proxy_cache_lock            on;proxy_cache_lock_timeout    200ms;proxy_temp_path             /tmpfs/proxy_temp;proxy_cache_path            /tmpfs/proxy_cache levels=1:2 keys_zone=cache:512m inactive=5m max_size=8g;proxy_connect_timeout       3s;proxy_read_timeout      3s;proxy_send_timeout      3s;

tmpfs(内存文件系统)

  1. location配置
location ~ ^/backend/(.*)$ {    #设置一致性哈希负载均衡key    set_by_lua_file $consistent_key "/export/App/c.3.cn/lua/lua_balacing_backend.properties";    #失败重试配置    proxy_next_upstream error timeout http_500 http_502 http_504    proxy_next_upstream_timeout 2s;    proxy_next_upstream_tries 2;    #请求上游服务器使用Get方法    proxy_method GET;    #不给上游服务器传递请求体    proxy_pass_request_body off;    #不给上游服务器传递请求头    proxy_pass_request_headers off;    #设置上游服务器的哪些响应头不发送给客户端    proxy_hide_header Vary;    #支持keep-alive    proxy_http_version 1.1;    proxy_set_header Connection "";    #给上游服务器传递Referer、Cookie和Host(按需)    proxy_set_header Referer $http_referer;    proxy_set_header Cookie $http_cookie;    proxy_set_header Host web.c.3.local;    proxy_pass http://backend /$1$is_args$args;}

开启gzip支持,减少数据包大小

gzip                on;gzip_min_length     1k;gzip_buffers        16 16k;grip_http_version   1.0;gzip_proxied        any;gzip_comp_level     2;gzip_types          text/plain application/x-javascript text/css;gzip_vary           on;

HTTP动态负载均衡

Consul是一款开源的分布式服务注册与发现系统

  • 服务注册
  • 服务发现
  • 故障检测
  • K/V存储
  • 多数据中心
  • Raft算法,实现集群数据一致性

可使用Consul-template实现配置模板,然后拉取Consul配置渲染模板来生成Nginx实际配置

Nginx四层负载均衡

静态负载均衡

./configure –prefix=/usr/servers –with-stream

  1. stream指令
    四层负载均衡是配置在stream指令下

    stream {    upstream mysql_backend {        ...    }    server {        ...    }}
  2. upstream配置

    upstream mysql_backend {    // 与http upstream类似}
  3. server配置

    server {    listen 3308;    #失败重试    proxy_next_upstream on;    proxy_next_upstream_timeout 0;    proxy_next_upstream_tries 0;    #超时设置    proxy_connect_timeout   1s;    proxy_timeout           1m;    #限速设置    proxy_upload_rate   0;  // 客户端,每秒字节数    proxy_download_rate 0;  // 上游服务器,每秒字节数}

    动态负载均衡

    nginx-stream-upsync-module 的兄弟模块 nginx-upsync-module 提供Http七层动态负载均衡,动态更新上游服务器不需要reload nginx,兼容nginx1.9.10+版本。提供了基于consul和etcd进行动态更新上游服务器的实现。

    ./configure --prefix=/usr/servers --with-stream --add-module=./nginx-stream-upsync-module