天天看點

nginx如何實作負載均衡、限流、緩存、黑白名單和灰階釋出

作者:運維老男孩

nginx負載均衡配置

1.負載均衡配置

http {
    upstream real_server {
       server 192.168.1.100:8082 weight=1;  #輪詢伺服器和通路權重
       server 192.168.1.100:8084 weight=2;
    }
    server {
        listen  80;
        location / {
            proxy_pass http://real_server;
        }
    }
}           

2.失敗重試配置

upstream real_server {
    server 192.168.1.100:8082 weight=1 max_fails=2 fail_timeout=60s;  #輪詢伺服器和通路權重
    server 192.168.1.100:8084 weight=2 max_fails=2 fail_timeout=60s;
 }           

在fail_timeout時間内失敗了max_fails次請求後,認為上遊伺服器不可用,就會将服務位址剔除掉,fail_timeout時間後會再次将伺服器加入存活清單進行重試。

nginx限流配置

limit_req_zone指令設定參數

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

參數說明

limit_req_zone定義在http塊中,$binary_remote_addr表示儲存用戶端IP位址的二進制形式。

Zone定義IP狀态及URL通路頻率的共享記憶體區域。zone=keyword辨別區域的名字,以及冒号後面跟區域大小。16000個IP位址的狀态資訊約1MB,例子區域可以存儲160000個IP位址。

Rate定義最大請求速率。示例中速率不能超過每秒10個請求。

設定限流

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

burs排隊大小,nodelay不限制單個請求間的時間。具體使用可以檢視高并發場景如何使用nginx實作限流-實戰篇

不限流白名單

geo $limit {
  default              1;
  192.168.1.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.1.0/24網段的ip通路是不限流的,其它限流。ip後面數字的含義

24表示子網路遮罩:255.255.255.0

16表示子網路遮罩:255.255.0.0

8表示子網路遮罩:255.0.0.0

nginx緩存設定

1.浏覽器緩存 靜态資源緩存用expire

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

Response Header中添加了Expires和Cache-Control

所謂的靜态資源一般包括一直不變的圖像,如網站的logo,js、css靜态檔案還有可下載下傳的内容,媒體檔案

協商緩存(add_header ETag/Last-Modified value)包括html檔案,經常替換的圖檔,經常需要修改的js、css檔案和基本不變的api接口

不需要緩存包括使用者隐私等敏感資料,使用者經常變動的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(key自定義,這邊用url的hash值)->v形式緩存到目錄裡,并根據需求對内容設定緩存時長,比如狀态碼為200緩存10分鐘,其餘的緩存1分鐘等待。要清理緩存可以借助purger的功能。如果ab測試/個性化需求時應禁用浏覽器緩存,否則會因為緩存導緻誤差。

nginx黑名單

方式一

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

方式二 lua+redis動态黑名單(openresty)

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           

配置(/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    = "127.0.0.1"
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           

nginx灰階釋出

1.根據cookie實作灰階釋出

根據cooke查詢version值,根據version跳轉到對應的host,如果沒有比對上的就跳轉到預設配置。

upstream host1 {
   server 192.168.2.100:2001 weight=1;  #輪詢伺服器和通路權重
   server 192.168.2.100:2002 weight=2;
}
upstream host2 {
   server 192.168.1.100:1111  max_fails=1 fail_timeout=60;
}
upstream default {
   server 192.168.1.100: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;
    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;
  }           

繼續閱讀