配置 5xx 比例超过 5% 时自动回滚到旧版本,使用 lua-resty-healthcheck
解读
国内灰度发布普遍采用“双集群”模型:新/旧版本分别对应 upstream A(canary)与 upstream B(stable)。题目要求“自动回滚”,意味着 Nginx 必须在运行时把流量从 A 全部切回 B,而无需人工 reload。5% 阈值要按“成功+失败”总量计算,而不是简单计数,且要避免因瞬时抖动频繁切换,因此必须引入滑动窗口与冷却期。lua-resty-healthcheck 只提供单节点健康探测,不直接给出“比例”统计,需要二次开发聚合逻辑。整套方案必须满足:
- 零中断:不能 reload、不能重启 worker;
- 高实时:统计窗口 10 s 内完成采样与决策;
- 可观测:每次切换都写错误日志并暴露 Prometheus 指标,方便 SRE 复盘;
- 可回滚:人为下发“强制回滚/强制灰度”指令时,Lua 逻辑立即生效。
知识点
- lua-resty-healthcheck 原理:基于 ngx.timer.every 的后台协程,通过 cosocket 发送 HTTP 探针,维护 target.state 表。
- ngx.shared.DICT 的 CAS 操作:安全地在多个 worker 之间累加 success、fail 计数。
- 滑动时间窗口:用环形数组 + 时间戳,避免全局锁,10 s 窗口 1 s 一个桶,过期桶自动清零。
- 流量切换手段:
a) balancer_by_lua 阶段动态 set_current_peer;
b) 使用“虚拟 Canary 节点”技术:upstream 只保留 stable 节点,canary 节点由 Lua 动态注入;当比例超阈值时,Lua 不再注入,即完成“回滚”。 - 冷却期与 hysteresis:进入回滚状态后,至少保持 120 s 不允许再次切回 canary,防止“抖动”。
- 指令通道:利用 ngx.shared 中的 command 标志位,运维通过 PUT /canary/status=disable 可立即强制回滚。
- 指标暴露:在 log_by_lua 中每请求累加,prometheus.lua 提供 /metrics,指标名:nginx_canary_5xx_ratio。
- 版本号传递:canary 节点在响应头加入 X-Version,方便客户端与监控识别。
答案
-
目录结构
/usr/local/openresty/site/lua/canary.lua # 核心逻辑
/usr/local/openresty/site/lua/stats.lua # 滑动窗口统计
/usr/local/openresty/site/lua/prometheus.lua # 指标暴露 -
关键代码
-- stats.lua
local window = 10
local buckets = {}
for i = 1, window do buckets[i] = {ok = 0, fail = 0, ts = 0} end
local idx = 1
local function record(is_ok)
local now = ngx.time()
local bucket = buckets[idx]
if bucket.ts ~= now then -- 新秒,换桶
bucket.ok, bucket.fail = 0, 0
bucket.ts = now
end
if is_ok then bucket.ok = bucket.ok + 1
else bucket.fail = bucket.fail + 1 end
end
local function ratio5xx()
local total_ok, total_fail = 0, 0
local expire = ngx.time() - window
for _, b in ipairs(buckets) do
if b.ts > expire then
total_ok = total_ok + b.ok
total_fail = total_fail + b.fail
end
end
if total_ok + total_fail == 0 then return 0 end
return total_fail / (total_ok + total_fail)
end
-- canary.lua
local stats = require "stats"
local prometheus = require "prometheus"
local shm = ngx.shared.canary_shm
local stable_list = {"10.0.0.1:80", "10.0.0.2:80"}
local canary_list = {"10.0.0.3:80", "10.0.0.4:80"}
local function should_use_canary()
local cmd = shm:get("force")
if cmd == "disable" then return false end
if cmd == "enable" then return true end
local cool = shm:get("cooldown")
if cool and cool > ngx.time() then return false end
return ratio5xx() < 0.05
end
local function _M.balancer()
local use_canary = should_use_canary()
local peers = use_canary and canary_list or stable_list
local idx = (ngx.worker_pid() + ngx.var.request_time) % #peers + 1
ngx.ctx.version = use_canary and "canary" or "stable"
return peers[idx]
end
local function _M.log()
local status = tonumber(ngx.var.status)
stats.record(status < 500)
prometheus:inc("canary_5xx_ratio", {}, ratio5xx())
-- 触发回滚判断
if ratio5xx() >= 0.05 and should_use_canary() then
shm:set("cooldown", ngx.time() + 120)
ngx.log(ngx.ERR, "canary 5xx ratio exceed 5%, rollback to stable")
end
end
return _M
- nginx.conf
lua_shared_dict canary_shm 1m;
init_worker_by_lua_block {
local stats = require "stats"
stats.rotate() -- 启动环形桶定时器
}
upstream stable {
server 0.0.0.1; # 占位,真实地址由 balancer 注入
balancer_by_lua_block {
local canary = require "canary"
local ip, port = canary.balancer()
ngx_balancer.set_current_peer(ip, port)
}
}
server {
listen 80;
location / {
proxy_pass http://stable;
header_filter_by_lua_block {
ngx.header["X-Version"] = ngx.ctx.version
}
log_by_lua_block {
require("canary").log()
}
}
location /canary/status {
content_by_lua_block {
local args = ngx.req.get_uri_args()
if args.set then
ngx.shared.canary_shm:set("force", args.set)
end
ngx.say("current force=", ngx.shared.canary_shm:get("force"))
}
}
location /metrics {
content_by_lua_block {
prometheus:collect()
}
}
}
- 验证步骤
a) 压测 canary 节点,制造 6% 5xx;
b) 10 s 内观察 /metrics 中 nginx_canary_5xx_ratio 超过 0.05;
c) 新请求全部不再命中 canary(X-Version 返回 stable),错误日志出现“rollback to stable”;
d) 120 s 冷却期内,即使 5xx 下降也不恢复;
e) 运维调用 curl http://gateway/canary/status?set=enable 可强制再次灰度。
拓展思考
- 多集群横向扩展:若 canary 与 stable 分属不同 K8s Service,可把 lua-resty-healthcheck 的 probe 对象指向 Service 的 ClusterIP,Lua 逻辑不变。
- 权重渐进回滚:不用“一刀切”,而是把 canary 权重从 100% 降到 50%、20%、0%,实现“梯度回滚”,需改造 balancer 阶段按权重随机。
- 与 Service Mesh 协同:Istio 本身提供基于 5xx 的自动回退(Circuit Breaker),但 North-South 流量仍走 Nginx Ingress,此时可把 Nginx 作为“大入口”,Mesh 做“东西向”,两级治理互不冲突。
- 双指标联合判断:除了 5xx 比例,再引入 P99 延迟 > 1 s 作为附加条件,只有两者同时触发才回滚,降低误杀。
- 蓝绿发布变种:回滚时不直接切回旧版本,而是把旧版本做一次“热升级”到最新稳定镜像,再切换,实现“回滚也保持版本最新”。