Nginx配置之負載均衡、限流、緩存、黑名單和灰度發佈

1、Nginx安裝(基於CentOS 6.5)css

1.yum命令安裝html

yum install nginx –y
(若不能安裝,執行命令yum install epel-release)node

2. 啓動、中止和重啓nginx

service nginx start
service nginx stop
service nginx restart
瀏覽器中 輸入服務器的 ip 地址,便可看到相應信息git

3. 其餘信息github

rpm -ql nginx 來查看安裝路徑
yum remove nginx 來卸載 
nginx -s reload 配置熱更新 web

2、Nginx負載均衡配置(/etc/nginx/nginx.conf)redis

  1. 負載均衡配置
http {
	   ……
    upstream real_server {
       server 192.168.103.100:2001 weight=1;  #輪詢服務器和訪問權重
       server 192.168.103.100:2002 weight=2;
    }

    server {
        listen  80;

        location / {
            proxy_pass http://real_server;
        }
    }
}
    2.失敗重試配置
    upstream real_server {
       server 192.168.103.100:2001 weight=1 max_fails=2 fail_timeout=60s;
       server 192.168.103.100:2002 weight=2 max_fails=2 fail_timeout=60s;
    }

意思是在fail_timeout時間內失敗了max_fails次請求後,則認爲該上游服務器不可用,而後將該服務地址踢除掉。fail_timeout時間後會再次將該服務器加入存活列表,進行重試。centos

3、Nginx限流配置api

  1. 配置參數

limit_req_zone指令設置參數 

limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s; 

1)limit_req_zone定義在http塊中,$binary_remote_addr表示保存客戶端IP地址的二進制形式。
2)Zone定義IP狀態及URL訪問頻率的共享內存區域。zone=keyword標識區域的名字,以及冒號後面跟區域大小。16000個IP地址的狀態信息約1MB,因此示例中區域能夠存儲160000個IP地址。
3)Rate定義最大請求速率。示例中速率不能超過每秒10個請求。

2.設置限流

location / {
	    limit_req zone=mylimit burst=20 nodelay;
	    proxy_pass http://real_server;
}

burst排隊大小,nodelay不限制單個請求間的時間

3.不限流白名單

geo $limit {
default 		     1;
192.168.2.0/24 	0;
}

map $limit $limit_key {
1 $binary_remote_addr;
0 "";
}

limit_req_zone $limit_key zone=mylimit:10m rate=1r/s;

location / {
	    limit_req zone=mylimit burst=1 nodelay;
	    proxy_pass http://real_server;
}

上述配置中,192.168.2.0/24網段的IP訪問是不限流的,其餘限流。

IP後面的數字含義:

24表示子網掩碼:255.255.255.0

16表示子網掩碼:255.255.0.0

8表示子網掩碼:255.0.0.0

4、Nginx緩存配置

  1. 瀏覽器緩存

靜態資源緩存用expire

location ~*  .(jpg|jpeg|png|gif|ico|css|js)$ {
   expires 2d;
}

Response Header中添加了Expires和Cache-Control


靜態資源包括(通常緩存)

1)普通不變的圖像,如logo,圖標等
2)js、css靜態文件
3)可下載的內容,媒體文件

協商緩存(add_header ETag/Last-Modified value)

1)HTML文件
2)常常替換的圖片
3)常常修改的js、css文件
4)基本不變的API接口

不須要緩存

1)用戶隱私等敏感數據

2)常常改變的api數據接口

2.代理層緩存

//緩存路徑,inactive表示緩存的時間,到期以後將會把緩存清理
proxy_cache_path /data/cache/nginx/ levels=1:2 keys_zone=cache:512m inactive = 1d max_size=8g;

location / {
    location ~ \.(htm|html)?$ {
        proxy_cache cache;
        proxy_cache_key    $uri$is_args$args;     //以此變量值作HASH,做爲KEY
        //HTTP響應首部能夠看到X-Cache字段,內容能夠有HIT,MISS,EXPIRES等等
        add_header X-Cache $upstream_cache_status;
        proxy_cache_valid 200 10m;
        proxy_cache_valid any 1m;
        proxy_pass  http://real_server;
        proxy_redirect     off;
    }
    location ~ .*\.(gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ {
        root /data/webapps/edc;
        expires      3d;
        add_header Static Nginx-Proxy;
    }
}

        在本地磁盤建立一個文件目錄,根據設置,將請求的資源以K-V形式緩存在此目錄當中,KEY須要本身定義(這裏用的是url的hash值),同時能夠根據須要指定某內容的緩存時長,好比狀態碼爲200緩存10分鐘,狀態碼爲301,302的緩存5分鐘,其餘全部內容緩存1分鐘等等。
        能夠經過purger的功能清理緩存。
        AB測試/個性化需求時應禁用掉瀏覽器緩存。

5、Nginx黑名單

1.通常配置

location / {
    deny  192.168.1.1;
    deny 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}

2. Lua+Redis動態黑名單(OpenResty)

1)安裝運行

yum install yum-utils
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
yum install openresty
yum install openresty-resty
查看
yum --disablerepo="*" --enablerepo="openresty" list available
運行
service openresty start

2) 配置(/usr/local/openresty/nginx/conf/nginx.conf)

    lua_shared_dict ip_blacklist 1m;

    server {
        listen  80;

        location / {
            access_by_lua_file lua/ip_blacklist.lua;
            proxy_pass http://real_server;
        }
    }

lua腳本(ip_blacklist.lua)

local redis_host    = "192.168.1.132"
local redis_port    = 6379
local redis_pwd     = 123456
local redis_db = 2

-- connection timeout for redis in ms.
local redis_connection_timeout = 100

-- a set key for blacklist entries
local redis_key     = "ip_blacklist"

-- cache lookups for this many seconds
local cache_ttl     = 60

-- end configuration

local ip                = ngx.var.remote_addr
local ip_blacklist 		= ngx.shared.ip_blacklist
local last_update_time 	= ip_blacklist:get("last_update_time");

-- update ip_blacklist from Redis every cache_ttl seconds:
if last_update_time == nil or last_update_time < ( ngx.now() - cache_ttl ) then

  local redis = require "resty.redis";
  local red = redis:new();

  red:set_timeout(redis_connect_timeout);

  local ok, err = red:connect(redis_host, redis_port);
  if not ok then
    ngx.log(ngx.ERR, "Redis connection error while connect: " .. err);
  else
    local ok, err = red:auth(redis_pwd)
    if not ok then
      ngx.log(ngx.ERR, "Redis password error while auth: " .. err);
    else
	    local new_ip_blacklist, err = red:smembers(redis_key);
	    if err then
		    ngx.log(ngx.ERR, "Redis read error while retrieving ip_blacklist: " .. err);
	    else
        ngx.log(ngx.ERR, "Get data success:" .. new_ip_blacklist)
		  -- replace the locally stored ip_blacklist with the updated values:
		    ip_blacklist:flush_all();
		  for index, banned_ip in ipairs(new_ip_blacklist) do
		    ip_blacklist:set(banned_ip, true);
		  end
		  -- update time
		  ip_blacklist:set("last_update_time", ngx.now());
      end
    end
  end
end

if ip_blacklist:get(ip) then
  ngx.log(ngx.ERR, "Banned IP detected and refused access: " .. ip);
  return ngx.exit(ngx.HTTP_FORBIDDEN);
end

6、Nginx灰度發佈

  1. 根據Cookie實現灰度發佈

根據Cookie查詢version值,若是該version值爲v1轉發到host1,爲v2轉發到host2,都不匹配的狀況下轉發默認。

    upstream host1 {
       server 192.168.2.46:2001 weight=1;  #輪詢服務器和訪問權重
       server 192.168.2.46:2002 weight=2;
    }

    upstream host2 {
       server 192.168.1.155:1111  max_fails=1 fail_timeout=60;
    }

    upstream default {
       server 192.168.1.153:1111  max_fails=1 fail_timeout=60;
    }

    map $COOKIE_version $group {
       ~*v1$ host1;
       ~*v2$ host2;
       default default;
    }

    lua_shared_dict ip_blacklist 1m;

    server {
        listen  80;

        #set $group "default";
        #if ($http_cookie ~* "version=v1"){
        #    set $group host1;
        #}
        #if ($http_cookie ~* "version=v2"){
        #    set $group host2;
        #}

        location / {
            access_by_lua_file lua/ip_blacklist.lua;
            proxy_pass http://$group;
        }
    }

2. 根據來路IP實現灰度發佈

server {
  ……………
  set $group default;
  if ($remote_addr ~ "192.168.119.1") {
      set $group host1;
  }
  if ($remote_addr ~ "192.168.119.2") {
      set $group host2;
  }

3. 更細粒度灰度發佈

可用lua腳本實現,參考開源項目:https://github.com/CNSRE/ABTestingGateway

 

PS:歡迎關注本人公衆號:Devin說。會有最新最及時的技術文檔推薦。

相關文章
相關標籤/搜索