Nginx配置之负载均衡、限流、缓存、黑名单和灰度发布

Nginx虚拟主机配置

基于虚拟主机配置域名

#当客户端访问www.itmayiedu.com,监听端口号为80,直接跳转到data/www目录下文件
    server {
        listen       80;
        server_name  www.itmayiedu.com;
        location / {
            root   data/www;
            index  index.html index.htm;
        }
    }
	#当客户端访问www.itmayiedu.com,监听端口号为80,直接跳转到data/bbs目录下文件
	 server {
        listen       80;
        server_name  bbs.itmayiedu.com;
        location / {
            root   data/bbs;
            index  index.html index.htm;
        }
    }

指定tomcat中的项目

 server_name  www.ydk.fun;
        location / {
            proxy_pass http://127.0.0.1:8080/MVNFHM/;
            proxy_set_header    REMOTE-HOST $remote_addr;
               proxy_set_header   Host $host;
               proxy_set_header   X-Real-IP $remote_addr;
               proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            #index  index.jsp index.htm;
        }

基于端口的虚拟主机

	#当客户端访问www.itmayiedu.com,监听端口号为8080,直接跳转到data/www目录下文件
	 server {
        listen       8080;
        server_name  8080.itmayiedu.com;
        location / {
            root   data/www;
            index  index.html index.htm;
        }
    }
	
	#当客户端访问www.itmayiedu.com,监听端口号为8081,直接跳转到data/bbs目录下文件
	 server {
        listen       8081;
        server_name  8081.itmayiedu.com;
        location / {
            root   data/bbs;
            index  index.html index.htm;
        }
    }

Nginx配置反向代理

反向代理的配置

###当客户端访问www.itmayiedu.com,监听端口号为80直接跳转到真实ip服务器地址 127.0.0.1:8080
	server {
        listen       80;
        server_name  www.itmayiedu.com;
        location / {
		 proxy_pass http://127.0.0.1:8080;
            index  index.html index.htm;
        }
}
###当客户端访问www.itmayiedu.com,监听端口号为80直接跳转到真实ip服务器地址 127.0.0.1:8081
	server {
        listen       80;
        server_name  8081.itmayiedu.com;
        location / {
		  proxy_pass http://127.0.0.1:8081;
            index  index.html index.htm;
        }
    }


Location正则表达式

location指令的作用是根据用户请求的URI来执行不同的应用,也就是根据用户请求的网站URL进行匹配,匹配成功即进行相关的操作。

已=开头表示精确匹配
如 A 中只匹配根目录结尾的请求,后面不能带任何字符串。
^~开头表示uri以某个常规字符串开头,不是正则匹配
~ 开头表示区分大小写的正则匹配;
~* 开头表示不区分大小写的正则匹配
/ 通用匹配, 如果没有其它匹配,任何请求都会匹配到
server {
        listen       80;
        server_name  www.itmayiedu.com;
		#精确匹配,注解后面不能带任何字符
        location =/ {
		    proxy_pass http://127.0.0.1:8080;
            index  index.html index.htm;
        }
}

	server {
        listen       80;
        server_name  www.itmayiedu.com;
		###  以开头/itmayiedu_8080 最终跳转到http://127.0.0.1:8080/;
        location /itmayiedu_8080/ {
		    proxy_pass http://127.0.0.1:8080/;
            index  index.html index.htm;
        }
		###  以开头/itmayiedu_8080 最终跳转到http://127.0.0.1:8081/;
		location /itmayiedu_8081/ {
		    proxy_pass http://127.0.0.1:8081/;
            index  index.html index.htm;
        }
    }

Nginx安装(基于CentOS 6.5)

1.yum命令安装

yum install nginx –y
(若不能安装,执行命令yum install epel-release)

  1. 启动、停止和重启

service nginx start
service nginx stop
service nginx restart
浏览器中 输入服务器的 ip 地址,即可看到相应信息

  1. 其他信息

rpm -ql nginx 来查看安装路径
yum remove nginx 来卸载
nginx -s reload 配置热更新

Nginx负载均衡配置(/etc/nginx/nginx.conf)

负载均衡配置

指定轮询几率

weight和访问比率成正比,用于后端服务器性能不均的情况

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;
        }
    }
}

ip_hash(访问ip)

每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。

upstream favresin{ 
      ip_hash; 
      server 10.0.0.10:8080; 
      server 10.0.0.11:8080; 
}

fair(第三方)

按后端服务器的响应时间来分配请求,响应时间短的优先分配。与weight分配策略类似。

 upstream favresin{      
      server 10.0.0.10:8080; 
      server 10.0.0.11:8080; 
      fair; 
}

url_hash(第三方)

按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。

注意:在upstream中加入hash语句,server语句中不能写入weight等其他的参数,hash_method是使用的hash算法。

 upstream resinserver{ 
      server 10.0.0.10:7777; 
      server 10.0.0.11:8888; 
      hash $request_uri; 
      hash_method crc32; 
}

失败重试配置

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

upstream还可以为每个设备设置状态值,这些状态值的含义分别如下:

down 表示单前的server暂时不参与负载.

weight 默认为1.weight越大,负载的权重就越大。

max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误.

fail_timeout : max_fails次失败后,暂停的时间。

backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

upstream bakend{ #定义负载均衡设备的Ip及设备状态 
      ip_hash; 
      server 10.0.0.11:9090 down; 
      server 10.0.0.11:8080 weight=2; 
      server 10.0.0.11:6060; 
      server 10.0.0.11:7070 backup; 
}

Nginx限流配置

配置参数

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

设置限流

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

burst排队大小,nodelay不限制单个请求间的时间

不限流白名单

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缓存配置

浏览器缓存

静态资源缓存用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数据接口

代理层缓存

//缓存路径,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黑名单

一般配置

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    = "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灰度发布

根据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;
    }
}

根据来路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;
  }

常用命令

查看端口

ps -ef|grep nginx

安装完gitlab后 nginx无法关闭

gitlab-ctl stop nginx
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值