運維篇—基於Nginx+Lua實現的灰度發佈
灰度發佈也叫 A/B 測試,原理是一套系統在實現了負載均衡,全國節點都部署了系統之後,可以在新功能上線後,讓一小部分用戶先使用,從中收集使用信息來做對比和發現bug,及時調整,最終分發到全國的節點。
而在目前很多公司都會使用nginx作為前端服務器,為後端服務器提供負載技術。當我們需要對後端服務器進行升級時,我們只想讓內部測試人員訪問到新升級的服務器上,生產環境用戶仍使用未升級的穩定環境。此時就可以使用nginx配合Lua模塊來實現一定程度的條件控制。(本文中就是以IP作為限制)
安裝環境
服務器 1: 192.168.1.214 (安裝apache作為後端服務器)
服務器 2: 192.168.1.215(安裝apache作為後端服務器)
服務器 3: 192.168.1.216 (安裝nginx+lua 前端服務器)
1.安裝nginx
準備工作
yum install -y pcre pcre-devel
yum install -y zlib zlib-devel
yum install -y openssl openssl-devel
下載地址://nginx.org/en/download.html
本文中使用是nginx-1.12.2版本
cd /data
wget //nginx.org/download/nginx-1.12.2.tar.gz
tar -zvxf nginx-1.12.2.tar.gz
cd nginx-1.12.2
./configure --prefix=/data/nginx --with-http_stub_status_module --with-http_ssl_module
make && make install
2.安裝Lua模塊
2.1安裝LuaJIT
下載地址://luajit.org/
wget //luajit.org/download/LuaJIT-2.0.4.tar.gz
tar zxvf LuaJIT-2.0.4.tar.gz
cd LuaJIT-2.0.4
make install PREFIX=/usr/local/luajit
echo "/usr/local/luajit/lib" > /etc/ld.so.conf.d/usr_local_luajit_lib.conf
ldconfig
export LUAJIT_LIB=/usr/local/luajit/lib
export LUAJIT_INC=/usr/local/luajit/include/luajit-2.0
2.2安裝ngx_devel_kit
下載地址https://github.com/simpl/ngx_devel_kit/tags
wget https://github.com/simpl/ngx_devel_kit/archive/v0.3.0.tar.gz
tar -zvxf v0.3.0.tar.gz
mv ngx_devel_kit-0.3.0/ ngx_devel_kit
2.3安裝lua-nginx-module
下載地址:https://github.com/openresty/lua-nginx-module/tags
wget https://github.com/openresty/lua-nginx-module/archive/v0.10.11rc3.tar.gz
tar -zvxg v0.10.11rc3.tar.gz
mv lua-nginx-module-0.10.11rc3/ lua-nginx-module
2.4 重新編譯NGINX安裝支持lua模塊
cd /data/nginx-1.12.2
#具體模塊路徑安裝時請修改
./configure --prefix=/data/nginx --with-http_stub_status_module --with-http_ssl_module --with-ld-opt="-Wl,-rpath,/usr/local/luajit/lib" --add-module=/data/ngx_devel_kit --add-module=/data/lua-nginx-module
make && make install
3.編寫lua腳本實現根據請求來源IP地址,匹配對應的location
cd /data/nginx
mkdir lua
cd lua
vim ip_gray.lua
#######以下為lua腳本
local ip_config = ngx.shared.config;
ClienIP=ngx.req.get_headers()["X-Real-IP"]
if ClientIP == nil then
ClientIP = ngx.req.get_headers()["x_forworded_for"]
end
if ClientIP == nil then
ClientIP = ngx.var.remote_addr
end
for line in io.lines("/data/nginx/lua/ipList.conf") do
if not ip_config:get(line) then
ip_config:set(line, "0")
end
end
if ip_config:get(ClientIP) == "0" then
ngx.exec("@test_env")
else
ngx.exec("@product_env")
end
#########以上為lua腳本
創建存放測試IP地址文件
vim ipList.conf
192.168.1.13
192.168.1.14
4.修改Nginx配置nginx.conf
下圖為主要配置
配置完畢後重啟Nginx,可在ipList.conf中添加IP地址測試,添加後nginx無需reload,刪除則需要reload。
lua_code_cache on | off 開啟或關閉Lua代碼緩存 生產環境一定要打開