Nginx使用进阶!分布式项目中的Nginx使用配置说明Nginx基

这是我参与11月更文挑战的第27天,活动详情查看:2021最后一次更文挑战

Nginx基本介绍

  • 分布式Nginx配置可以实现:
    • 负载均衡
    • 限流配置
    • 缓存
    • 黑白名单
    • 灰度发布

Nginx安装

  • CentOS环境下安装Nginx

安装依赖

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

安装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
./configure --prefix=/usr/local/openssl-1.0.2s
make
make install
复制代码

安装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
复制代码

安装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 install
复制代码

安装Nginx

  • 安装Nginx时,需要指定openssl, pcre, zlib的源码解压目录
  • 安装完成后Nginx配置文件的完整路径 : usr/local/nginx-1.17.2/conf/nginx.conf
wget https://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负载均衡

负载均衡配置

http {
	...
	upstream servers {
		# 配置轮询服务器和权重
		server 192.168.6.66:6000 weight=1;
		server 192.168.6.66:6001 weight=2;
	}

	server {
		listen 80;
		location / {
			proxy_pass http://servers;
		}
	}
}
复制代码

失败重试配置

upstream servers {
	server 192.168.6.66:6001 weight=1 max_fails=2 fail_timeout=60s;
	server 192.168.6.66:6002 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=customelimit:10m rate=10r/s;
复制代码
  • limit_req_zone : 定义在http块中
    • $binary_remote_addr : 表示保存客户端IP地址的二进制形式
    • zone : 定义IP状态以及URL访问频率的共享内存区域
      • zone=keyword : 标识区域的名称,冒号后面标识区域的大小 . 1MB大约可以存储16000IP地址的状态信息,所以这里区域可以存储160000IP地址的状态信息
    • Rate : 定义最大请求速率. 这里的速率不能超过每秒10个请求

Nginx限流设置

location / {
	limit_req zone=customelimit burst=20 nodelay;
	proxy_pass http://servers;
}
复制代码
  • 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=customelimit:10m rate=1r/s;

location / {
	limit_req zone=customelimit burst=1 nodelay;
	proxy_pass http://servers;
}
复制代码
  • 这里配置192.168.2.0/24网段的IP地址为限流白名单,访问是不限流的,其余的网段限流

Nginx缓存配置

浏览器缓存

  • 静态资源缓存使用expires :
location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
	expires 2d;
}
复制代码
  • Response Header中添加了ExpiresCache-Control
  • 静态资源缓存:
    • 普通不变的图像. 比如logo,图标等
    • js,css静态文件
    • 可下载的内容,媒体文件
  • 协商缓存: add_header ETag或者Last-Modified value
    • HTML文件
    • 经常替换的图片
    • 经常修改的js,css文件
    • 基本不变的API接口
  • 不需要缓存的数据:
    • 用户隐私等敏感数据
    • 经常改变的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;
		# 将该变量值做hash,作为key
		proxy_cache_key $uri$is_args$args;
		# 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://servers;
		proxy_redirect off;
	}	

	location ~ .*\.(gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ {
		root /data/webapps/edc;
		expires 3d;
		add_header Static Nginx_Proxy;
	}
}
复制代码
  • 在本地磁盘创建一个文件目录,根据设置,将请求的资源以key-value形式缓存在这个文件目录中
    • key需要定义,这里使用的是urlhash
    • 同时可以根据需要指定某缓存内容的缓存时长
      • 状态码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;
}
复制代码

动态黑白名单

  • 使用OpenResty实现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
# 查看openresty是否安装成功
yum --disablerepo="*" --enablerepo="openresty" list available
# 运行openresty
service openresty start
复制代码
  • OpenRestynginx配置: /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://servers;
	}
}
复制代码
  • lua脚本: ip_blacklist.lua
local redis_host = "192.168.1.132"
local redis_port = 6379
local redis_pwd = 123456
local redis_db = 2

-- 连接超时时间 ms
local redis_connection_timeout = 100

-- 设置黑名单键
local redis_key = "ip_blacklist"

-- 缓存查找时间 s
local cache_ttl = 60
-- Redis配置结束

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

-- 每次缓存查找时间之后从缓存Redis中更新黑名单ip_blackList
if last_update_time == nil or last_update_time < ( ngx.now() - cache_ttl ) then
	local redis = require "resty.redis";
	local red = redis:new();
	
	redis: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);
				-- 使用更新的黑名单值new_ip_blacklist替换本地存储的黑名单值ip_blacklist
				ip_blacklist:flush_all();
				for index, banned_ip in ipairs(new_ip_blacklist) do
				ip_blacklist:set(banned_ip, true);
				end
				-- 记录更新时间
				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
    • 如果version值为v2则转发到host2
    • 如果version值都没有匹配则转发到默认配置
upstream host1 {
	server 192.168.2.46:2001 weight = 1;
	server 192.168.2.46.2003 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 "dafault";
	# 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 {
	listen 80;
	set $group "dafault";
	if ($remote_addr ~ "192.168.119.1") {
		set $group host1;
	}
	if ($remote_addr ~ "192.168.119.2") {
		set $group host2;
	}
}
复制代码