灰度发布(金丝雀发布)是一种渐进式发布策略,允许你将新版本逐步推送给部分用户。以下是使用Nginx实现简单前端灰度系统的几种方法:
upstream production {
server 192.168.1.100:8080;
}
upstream canary {
server 192.168.1.101:8080;
}
server {
listen 80;
server_name example.com;
# 默认使用生产环境
set $upstream "production";
# 检查是否存在灰度cookie
if ($http_cookie ~* "canary=true") {
set $upstream "canary";
}
location / {
proxy_pass http://$upstream;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
upstream production {
server 192.168.1.100:8080;
}
upstream canary {
server 192.168.1.101:8080;
}
server {
listen 80;
server_name example.com;
# 默认使用生产环境
set $upstream "production";
# 特定IP段使用灰度环境
if ($remote_addr ~ "192.168.1.(10[0-9]|11[0-9])") {
set $upstream "canary";
}
location / {
proxy_pass http://$upstream;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
使用Nginx的split_clients模块实现按比例分流:
upstream production {
server 192.168.1.100:8080;
}
upstream canary {
server 192.168.1.101:8080;
}
split_clients "${remote_addr}${http_user_agent}" $variant {
10% canary;
* production;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://$variant;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
upstream production {
server 192.168.1.100:8080;
}
upstream canary {
server 192.168.1.101:8080;
}
server {
listen 80;
server_name example.com;
# 默认使用生产环境
set $upstream "production";
# 检查URL参数
if ($arg_canary = "true") {
set $upstream "canary";
}
location / {
proxy_pass http://$upstream;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
如果需要更复杂的灰度规则,可以结合OpenResty的Lua脚本:
http {
lua_package_path "/path/to/lua/scripts/?.lua;;";
upstream production {
server 192.168.1.100:8080;
}
upstream canary {
server 192.168.1.101:8080;
}
server {
listen 80;
server_name example.com;
location / {
access_by_lua_file /path/to/canary.lua;
proxy_pass http://$upstream;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
}
对应的Lua脚本(canary.lua
)可以包含更复杂的逻辑,如:
- 用户ID哈希
- 设备类型检测
- 地理位置判断
- AB测试分组
以上方案可以根据实际需求组合使用,实现更灵活的灰度发布策略。