引言
零停机的核心不是部署命令,而是让新旧版本在过渡期共存:数据库兼容、会话可用、流量可切换、失败可回滚。
健康检查
健康检查是流量切换的门禁。就绪检查确认实例能处理请求,存活检查确认进程需要重启。检查要有超时、区分依赖故障,并避免在启动完成前通过。
滚动、蓝绿与金丝雀
滚动更新逐个替换实例,成本低但新旧版本共存时间长。蓝绿部署同时运行两套环境,切换瞬间完成,但资源翻倍。金丝雀先放小比例流量,用指标验证后再扩大。选择取决于风险和基础设施。
功能开关与回滚
功能开关把部署与发布解耦,出问题时关闭开关比回滚更快。回滚路径必须始终可用并定期演练:保留旧镜像、旧配置和数据库兼容性。回滚不是失败,是正常操作。
数据库与会话
数据库变更使用 expand-contract,确保新旧代码都能读写。需要粘性会话时,在切换前排空或使用共享会话存储。部署后监控错误率、延迟和关键业务指标,确认无回退。
代码示例
let ready = false;
app.get("/health", (req, res) => res.status(ready ? 200 : 503).end());
// Mark ready only after dependencies are connected and migrations are checked.
async function start() {
await db.connect();
await redis.connect();
await runMigrationsIfSafe();
ready = true;
app.listen(3000);
}
# A rolling update with a health gate (Docker Compose / Swarm style).
deploy:
replicas: 6
update_config:
parallelism: 2 # update 2 at a time
delay: 10s # wait between batches
order: start-first # start new before stopping old
failure_action: rollback
// The router switch is a single atomic update.
function switchTraffic(target: "blue" | "green") {
router.update({ default: { service: target, weight: 100 } });
}
// Deploy: build green, wait for healthy, switch, keep blue as rollback.
// Weighted routing for a canary.
router.update({
default: { service: "blue", weight: 99 },
canary: { service: "green", weight: 1 },
});
// Automated promotion gate: expand only if the canary's error rate is below threshold.
async function promoteCanary() {
const errorRate = await metrics.errorRate({ service: "green", window: "5m" });
const p99 = await metrics.p99Latency({ service: "green", window: "5m" });
if (errorRate > 0.01 || p99 > 2000) return rollback();
await rampTraffic("green", [10, 50, 100]); // expand in steps
}
if (flags.isEnabled("new-checkout", user.id)) {
return newCheckout(user);
}
return oldCheckout(user);
1. Expand: ALTER TABLE users ADD COLUMN email_verified BOOLEAN DEFAULT false; -- nullable, old code unaffected
2. Deploy: new version writes email_verified, backfills existing rows to false
3. Constrain: ALTER TABLE users ALTER COLUMN email_verified SET NOT NULL; -- safe, no nulls remain
4. Contract: (after old version retired) remove the old column the new code does not use
# Kubernetes: a rolling update with a grace period for connection draining.
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0 # never below the desired count -> always serving
terminationGracePeriodSeconds: 30 # 30s to finish in-flight requests before SIGKILL