【Nginx】实现负载均衡、限流、缓存、黑白名单和灰度发布,这是最全的一篇了!

本文涉及的产品
云原生内存数据库 Tair,内存型 2GB
云数据库 Redis 版,标准版 2GB
推荐场景:
搭建游戏排行榜
传统型负载均衡 CLB,每月750个小时 15LCU
简介: 在《【高并发】面试官问我如何使用Nginx实现限流,我如此回答轻松拿到了Offer!》一文中,我们主要介绍了如何使用Nginx进行限流,以避免系统被大流量压垮。除此之外,Nginx还有很多强大的功能,例如:负载均衡、缓存、黑白名单、灰度发布等。今天,我们就来一起探讨Nginx支持的这些强大的功能!

Nginx安装

注意:这里以CentOS 6.8服务器为例,以root用户身份来安装Nginx。

1.安装依赖环境

yum -y install wget gcc-c++ ncurses ncurses-devel cmake make perl bison openssl openssl-devel gcc* libxml2 libxml2-devel curl-devel libjpeg* libpng* freetype* autoconf automake zlib* fiex* libxml* libmcrypt* libtool-ltdl-devel* libaio libaio-devel  bzr libtool

2.安装openssl

wget https://www.openssl.org/source/openssl-1.0.2s.tar.gz
tar -zxvf openssl-1.0.2s.tar.gz
cd /usr/local/src/openssl-1.0.2s
./config --prefix=/usr/local/openssl-1.0.2s
make
make install

3.安装pcre

wget https://ftp.pcre.org/pub/pcre/pcre-8.43.tar.gz
tar -zxvf pcre-8.43.tar.gz
cd /usr/local/src/pcre-8.43
./configure --prefix=/usr/local/pcre-8.43
make
make install

4.安装zlib

wget https://sourceforge.net/projects/libpng/files/zlib/1.2.11/zlib-1.2.11.tar.gz
tar -zxvf zlib-1.2.11.tar.gz
cd /usr/local/src/zlib-1.2.11
./configure --prefix=/usr/local/zlib-1.2.11
make
make

5.安装Nginx

wget http://nginx.org/download/nginx-1.17.2.tar.gz
tar -zxvf nginx-1.17.2.tar.gz
cd /usr/local/src/nginx-1.17.2
./configure --prefix=/usr/local/nginx-1.17.2 --with-openssl=/usr/local/src/openssl-1.0.2s --with-pcre=/usr/local/src/pcre-8.43 --with-zlib=/usr/local/src/zlib-1.2.11 --with-http_ssl_module
make
make install

这里需要注意的是:安装Nginx时,指定的是openssl、pcre和zlib的源码解压目录,安装完成后Nginx配置文件的完整路径为:/usr/local/nginx-1.17.2/conf/nginx.conf。

Nginx负载均衡配置

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时间后会再次将该服务器加入存活列表,进行重试。

Nginx限流配置

1.配置参数

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个请求。

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

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-V形式缓存在此目录当中,KEY需要自己定义(这里用的是url的hash值),同时可以根据需要指定某内容的缓存时长,比如状态码为200缓存10分钟,状态码为301,302的缓存5分钟,其他所有内容缓存1分钟等等。

可以通过purger的功能清理缓存。

AB测试/个性化需求时应禁用掉浏览器缓存。

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)

安装运行

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    = "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

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.更细粒度灰度发布

参考:

https://github.com/sunshinelyz/ABTestingGateway

相关实践学习
SLB负载均衡实践
本场景通过使用阿里云负载均衡 SLB 以及对负载均衡 SLB 后端服务器 ECS 的权重进行修改,快速解决服务器响应速度慢的问题
负载均衡入门与产品使用指南
负载均衡(Server Load Balancer)是对多台云服务器进行流量分发的负载均衡服务,可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性。 本课程主要介绍负载均衡的相关技术以及阿里云负载均衡产品的使用方法。
相关文章
|
1月前
|
缓存 应用服务中间件 nginx
成功解决 Nginx更新静态资源无效 ,Nginx静态资源更新不及时,Nginx清除缓存
这篇文章讨论了在使用Nginx进行动静分离时遇到的静态资源更新不及时的问题。问题描述了在服务器上更新静态资源后,访问页面时页面没有显示更新的情况。文章提供了解决这个问题的方法,即清除浏览器缓存,并提供了相关参考文章链接。此外,还展示了问题复现的步骤和正常情况的预期结果。
成功解决 Nginx更新静态资源无效 ,Nginx静态资源更新不及时,Nginx清除缓存
|
8天前
|
负载均衡 网络协议 Unix
Nginx负载均衡与故障转移实践
Nginx通过ngx_http_upstream_module模块实现负载均衡与故障转移,适用于多服务器环境。利用`upstream`与`server`指令定义后端服务器组,通过`proxy_pass`将请求代理至这些服务器,实现请求分发。Nginx还提供了多种负载均衡策略,如轮询、权重分配、IP哈希等,并支持自定义故障转移逻辑,确保系统稳定性和高可用性。示例配置展示了如何定义负载均衡设备及状态,并应用到具体server配置中。
|
30天前
|
负载均衡 应用服务中间件 Linux
"揭晓nginx的神秘力量:如何实现反向代理与负载均衡,拯救服务器于水火?"
【8月更文挑战第20天】在Linux环境下,nginx作为高性能HTTP服务器与反向代理工具,在网站优化及服务器负载均衡中扮演重要角色。本文通过电商平台案例,解析nginx如何解决服务器压力大、访问慢的问题。首先介绍反向代理原理,即客户端请求经由代理服务器转发至内部服务器,隐藏真实服务器地址;并给出配置示例。接着讲解负载均衡原理,通过将请求分发到多个服务器来分散负载,同样附有配置实例。实践表明,采用nginx后,不仅服务器压力得到缓解,还提升了访问速度与系统稳定性。
46 3
|
30天前
|
负载均衡 算法 应用服务中间件
在Linux中,nginx反向代理和负载均衡实现原理是什么?
在Linux中,nginx反向代理和负载均衡实现原理是什么?
|
1月前
|
负载均衡 应用服务中间件 nginx
Nginx怎么去做负载均衡?
Nginx的负载均衡器配置就完成了,而且由于Nginx的配置文件结构清晰而且简洁,调整和维护也相对方便。通过上述步骤,你可以将Nginx设置为一款强大的负载均衡器,提升服务器集群的处理能力及高可用性。
34 4
|
1月前
|
应用服务中间件 Linux nginx
高并发下Nginx配置限流
【8月更文挑战第16天】
47 1
|
1月前
|
负载均衡 监控 网络协议
Nginx:负载均衡小专题(三)
Nginx:负载均衡小专题(三)
76 1
|
27天前
|
负载均衡 应用服务中间件 Linux
在Linux中,Nginx如何实现负载均衡分发策略?
在Linux中,Nginx如何实现负载均衡分发策略?
|
5天前
|
canal 缓存 NoSQL
Redis缓存与数据库如何保证一致性?同步删除+延时双删+异步监听+多重保障方案
根据对一致性的要求程度,提出多种解决方案:同步删除、同步删除+可靠消息、延时双删、异步监听+可靠消息、多重保障方案
Redis缓存与数据库如何保证一致性?同步删除+延时双删+异步监听+多重保障方案
|
21天前
|
缓存 NoSQL Java
Redis深度解析:解锁高性能缓存的终极武器,让你的应用飞起来
【8月更文挑战第29天】本文从基本概念入手,通过实战示例、原理解析和高级使用技巧,全面讲解Redis这一高性能键值对数据库。Redis基于内存存储,支持多种数据结构,如字符串、列表和哈希表等,常用于数据库、缓存及消息队列。文中详细介绍了如何在Spring Boot项目中集成Redis,并展示了其工作原理、缓存实现方法及高级特性,如事务、发布/订阅、Lua脚本和集群等,帮助读者从入门到精通Redis,大幅提升应用性能与可扩展性。
45 0