阶段2(下):运维专题 Docker/Nginx/Linux/CI-CD/Git 的课程、企业场景、面试题和可运行示例

This commit is contained in:
Shikui Wang committed 2026-10-23 15:36:06 +08:00
1 parent 5eb67c5d08
commit b8010a74f3
42 files changed
+3533 -55

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
---
id: devops.nginx.proxy-static
title: 反向代理、负载均衡和静态资源:location 匹配、proxy_pass、SPA 回退
type: lesson
domain: devops
stack: [nginx]
tags: [反向代理, location, proxy_pass, upstream, try_files, gzip]
level: basic
est_hours: 2
related: [devops.nginx.https-stream-limit, devops.nginx.interview]
week: [3, 7]
order: 1
---
# 反向代理、负载均衡和静态资源:location 匹配、proxy_pass、SPA 回退
## 解释说明
- **正向代理 vs 反向代理**:正向代理代表客户端(翻墙代理),服务器不知道真实客户端;反向代理代表服务端,客户端只看到 Nginx,不知道后面有几台服务器。
- **配置结构**:`http` → `server`(按域名和端口区分站点)→ `location`(按路径匹配)。
- **location 匹配优先级**:`=` 精确匹配最高;然后找最长的前缀匹配,如果它带 `^~` 就直接用;否则按配置顺序检查正则(`~` 区分大小写、`~*` 不区分),第一个匹配的正则胜出;都不匹配就用最长前缀。
- **`proxy_pass` 末尾的斜杠**:`location /api/ { proxy_pass http://backend; }` 会把 `/api/users` 原样转发;`proxy_pass http://backend/;`(带路径)会把匹配的 `/api/` 替换成 `/`,后端收到 `/users`。
- **转发真实客户端信息**:后端看到的来源 IP 是 Nginx,要通过 `X-Real-IP`、`X-Forwarded-For`、`X-Forwarded-Proto` 传递;后端框架要配置信任这个代理(Gin 的 `SetTrustedProxies`、Uvicorn 的 `--forwarded-allow-ips`)。
- **负载均衡**:`upstream` 中列多个 server,默认轮询;还有 `weight` 权重、`least_conn` 最少连接、`ip_hash` 同一 IP 固定到同一台。`max_fails` / `fail_timeout` 做被动健康检查。
- **静态资源**:`root` 拼接路径(`root /var/www;` + `/a.js` → `/var/www/a.js`),`alias` 替换路径;SPA 用 `try_files $uri $uri/ /index.html;` 把前端路由回退到 index.html;带哈希的静态文件设长缓存,`index.html` 不缓存;开启 `gzip`。
## 案例
前后端分离部署在一台服务器:`/` 是 Vue / React 打包后的静态文件,`/api/` 转发到两台 Go API 实例,`/ai/` 转发到 Python AI 服务。刷新 `/orders/42` 时出现 404,原因是没有配置 `try_files` 回退。
## 代码示例
```nginx
upstream api {
least_conn;
server 127.0.0.1:8081 max_fails=3 fail_timeout=10s; # 示例:两个后端实例
server 127.0.0.1:8082 max_fails=3 fail_timeout=10s;
keepalive 32; # 和后端保持长连接
}
server {
listen 80;
server_name example.com;
root /var/www/app/dist;
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;
location / {
try_files $uri $uri/ /index.html; # SPA 前端路由回退
}
location = /index.html {
add_header Cache-Control "no-cache"; # 入口文件不缓存,发版立即生效
}
location /assets/ {
expires 1y; # 文件名带哈希,可以长缓存
add_header Cache-Control "public, immutable";
}
location /api/ {
proxy_pass http://api; # 不带路径:/api/users 原样转发
proxy_http_version 1.1;
proxy_set_header Connection ""; # 配合 keepalive
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 3s;
proxy_read_timeout 30s;
}
}
```
可在本机用真实 Nginx 验证的完整配置和测试见 [examples/gateway](examples/gateway/)。修改配置后先 `nginx -t` 检查语法,再 `nginx -s reload` 平滑重载。
## 易错点
- **`proxy_pass` 带不带斜杠搞混**:后端收到的路径多了或少了 `/api`,表现为 404。
- **`root` 和 `alias` 搞混**:`location /static/ { alias /data/files/; }` 中 alias 末尾的斜杠要和 location 一致。
- **SPA 没配 `try_files`**:刷新非首页路由 404。
- **`index.html` 被长缓存**:发版后用户还在用旧页面、引用已删除的旧资源。
- **后端拿到的 IP 全是 Nginx 的**:没传 `X-Forwarded-For` 或后端没配置可信代理;反过来,盲目信任该头会被伪造。
- **改完配置直接 reload 不先 `nginx -t`**:语法错误时 reload 失败(旧配置继续运行),但如果是 restart 就直接起不来了。
## 面试常问
见 [Nginx 面试题](interview.md):正向和反向代理、location 优先级、负载均衡策略、proxy_pass 斜杠问题。
@@ -0,0 +1,113 @@
---
id: devops.nginx.https-stream-limit
title: HTTPS、SSE / WebSocket、限流和灰度
type: lesson
domain: devops
stack: [nginx]
tags: [HTTPS, TLS, SSE, WebSocket, limit_req, 灰度发布]
level: intermediate
prerequisites: [devops.nginx.proxy-static]
est_hours: 3
related: [devops.nginx.scenario.ai-gateway-sse-canary, devops.nginx.interview]
week: [7, 14]
order: 2
---
# HTTPS、SSE / WebSocket、限流和灰度
## 解释说明
**HTTPS**
- 证书可以用 Let's Encrypt(免费,certbot 或 acme.sh 自动续期)或云厂商证书。
- 配置 `ssl_certificate`、`ssl_certificate_key`,只开启 TLS 1.2 / 1.3;80 端口 301 跳转到 443。
- TLS 在 Nginx 终止,Nginx 到内网后端用 HTTP(`X-Forwarded-Proto: https` 告诉后端原始协议)。
**SSE(大模型流式输出)**
- SSE 是普通 HTTP 响应(`Content-Type: text/event-stream`),服务端不断写入 `data: ...\n\n`。
- Nginx 默认开启 `proxy_buffering`,会把后端响应先攒进缓冲区,导致用户看到的“打字机效果”变成一大段一起出现。**关闭缓冲**:`proxy_buffering off;`,或者后端返回响应头 `X-Accel-Buffering: no`。
- 生成时间长,`proxy_read_timeout` 要调大(它是两次读之间的间隔,不是总时长);也可以让后端定期发心跳注释 `: ping`。
- 如果开启了 gzip,确认流式响应不被压缩缓冲(`text/event-stream` 不在 `gzip_types` 中即可)。
**WebSocket**:需要协议升级头:
```nginx
map $http_upgrade $connection_upgrade { default upgrade; "" close; }
location /ws/ {
proxy_pass http://ws_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_read_timeout 3600s;
}
```
**限流**:`limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;` 定义按 IP 的漏桶;`limit_req zone=api burst=20 nodelay;` 允许突发 20 个且不排队延迟;超出返回 `limit_req_status`(默认 503,建议改成 429)。`limit_conn` 限制并发连接数。
**灰度发布**:
- 按比例:`split_clients "${remote_addr}" $variant { 10% canary; * stable; }`;
- 按用户:`map $cookie_canary $backend { default stable; "1" canary; }`,内部员工或白名单用户先体验;
- 按权重:`upstream` 里新旧实例设置不同 `weight`。
## 案例
AI 问答页面上线后用户反馈“回答要等很久才一下子全部出来”:浏览器直连后端是逐字输出,经过 Nginx 就变成整段。原因是 `proxy_buffering` 默认开启。关闭后恢复逐字输出;同时把 `proxy_read_timeout` 从 60 秒调到 300 秒,避免长回答被中途断开(504)。
## 代码示例
```nginx
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;
map $cookie_canary $api_backend {
default api_stable;
"1" api_canary;
}
server {
listen 443 ssl;
http2 on; # nginx 1.25.1+ 的写法;旧版本写在 listen 后面
server_name example.com;
ssl_certificate /etc/nginx/certs/fullchain.pem;
ssl_certificate_key /etc/nginx/certs/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
location /api/ {
limit_req zone=api_limit burst=5 nodelay;
limit_req_status 429;
proxy_pass http://$api_backend;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /ai/stream {
proxy_pass http://api_stable;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off; # 流式输出必须关闭缓冲
proxy_cache off;
proxy_read_timeout 300s;
}
}
```
[examples/gateway](examples/gateway/) 的测试里验证了:关闭缓冲时第一条 SSE 事件在约 0.3 秒内到达,而整个响应约 0.9 秒结束;打开缓冲时第一条事件要等整个响应结束才到达。
## 易错点
- **SSE 没关缓冲**:流式变整段。
- **`proxy_read_timeout` 太短**:长回答被 504 中断。
- **WebSocket 没加 Upgrade / Connection 头**:握手失败,前端报 400 或连接立即关闭。
- **限流按 `$remote_addr` 但前面还有一层负载均衡**:所有请求的地址都是负载均衡器,一起被限流。要用 `real_ip` 模块从可信代理的头里取真实 IP。
- **证书过期**:自动续期任务失败没人发现。加监控告警。
- **灰度只切了后端没切前端资源**(或反过来):前后端版本不匹配。灰度规则要一致,接口要向后兼容。
## 面试常问
见 [Nginx 面试题](interview.md):SSE 代理要注意什么、WebSocket 代理配置、限流原理、灰度发布怎么做、502 和 504 的区别。
@@ -0,0 +1,63 @@
# 网关示例:静态前端 + /api 反向代理 + /ai/stream SSE 流式代理 + 限流 + 按 Cookie 灰度
# 运行 test_gateway.py 时会把 {{...}} 占位符替换成临时端口和目录
worker_processes 1;
error_log {{PREFIX}}/error.log warn;
pid {{PREFIX}}/nginx.pid;
events { worker_connections 256; }
http {
access_log off;
# 非 root 运行时,把临时文件目录放到可写位置
client_body_temp_path {{PREFIX}}/client_body;
proxy_temp_path {{PREFIX}}/proxy;
fastcgi_temp_path {{PREFIX}}/fastcgi;
uwsgi_temp_path {{PREFIX}}/uwsgi;
scgi_temp_path {{PREFIX}}/scgi;
# 每个 IP 每秒 5 个请求,突发最多 5 个
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;
limit_req_status 429;
upstream api_stable { server 127.0.0.1:{{STABLE_PORT}}; keepalive 16; }
upstream api_canary { server 127.0.0.1:{{CANARY_PORT}}; keepalive 16; }
# Cookie canary=1 的用户走新版本,其余走稳定版本
map $cookie_canary $api_backend {
default api_stable;
"1" api_canary;
}
server {
listen 127.0.0.1:{{LISTEN_PORT}};
# 前端单页应用:找不到文件时回退到 index.html,交给前端路由
location / {
root {{PREFIX}}/html;
try_files $uri $uri/ /index.html;
}
location /api/ {
limit_req zone=api_limit burst=5 nodelay;
proxy_pass http://$api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 3s;
proxy_read_timeout 30s;
}
# 大模型流式输出(SSE):关闭缓冲,否则 Nginx 攒满缓冲区才发给浏览器
location /ai/stream {
proxy_pass http://api_stable;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 300s; # 生成时间长,读超时要放宽
add_header X-Accel-Buffering no;
}
}
}
@@ -0,0 +1,130 @@
"""用真实的 Nginx 验证网关配置:反向代理、SPA 回退、SSE 不缓冲、限流、Cookie 灰度。
运行:python -m pytest -q test_gateway.py(需要本机安装 nginx;没有安装时自动跳过)
测试会启动两个 Python 后端(稳定版 / 灰度版)和一个非 root 的 Nginx,全部使用临时端口和临时目录。
"""
import http.client
import shutil
import socket
import subprocess
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import pytest
NGINX = shutil.which("nginx") or ("/usr/sbin/nginx" if Path("/usr/sbin/nginx").exists() else None)
pytestmark = pytest.mark.skipif(NGINX is None, reason="没有安装 nginx")
HERE = Path(__file__).resolve().parent
def free_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def backend(version: str) -> ThreadingHTTPServer:
class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a): # 安静
pass
def do_GET(self):
if self.path.startswith("/ai/stream"):
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Connection", "close")
self.end_headers()
for i in range(3):
self.wfile.write(f"data: token{i}\n\n".encode())
self.wfile.flush()
time.sleep(0.3)
self.close_connection = True
return
body = f'{{"version":"{version}","xff":"{self.headers.get("X-Forwarded-For", "")}"}}'.encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
srv = ThreadingHTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
@pytest.fixture(scope="module")
def gateway(tmp_path_factory):
prefix = tmp_path_factory.mktemp("nginx")
(prefix / "html").mkdir()
(prefix / "html" / "index.html").write_text("<div id=app>SPA</div>")
stable, canary = backend("stable"), backend("canary")
port = free_port()
conf = (HERE / "nginx.conf.template").read_text()
for k, v in {"PREFIX": str(prefix), "STABLE_PORT": stable.server_address[1],
"CANARY_PORT": canary.server_address[1], "LISTEN_PORT": port}.items():
conf = conf.replace("{{" + k + "}}", str(v))
(prefix / "nginx.conf").write_text(conf)
check = subprocess.run([NGINX, "-t", "-p", str(prefix), "-c", str(prefix / "nginx.conf")],
capture_output=True, text=True)
assert check.returncode == 0, check.stderr
proc = subprocess.Popen([NGINX, "-p", str(prefix), "-c", str(prefix / "nginx.conf"), "-g", "daemon off;"],
stderr=subprocess.PIPE)
for _ in range(50):
try:
socket.create_connection(("127.0.0.1", port), timeout=0.1).close()
break
except OSError:
time.sleep(0.1)
yield port
proc.terminate()
proc.wait(5)
stable.shutdown()
canary.shutdown()
def get(port: int, path: str, headers: dict | None = None) -> tuple[int, str]:
c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
c.request("GET", path, headers=headers or {})
r = c.getresponse()
body = r.read().decode()
c.close()
return r.status, body
def test_spa_fallback(gateway):
assert get(gateway, "/orders/42") == (200, "<div id=app>SPA</div>")
def test_proxy_and_canary(gateway):
status, body = get(gateway, "/api/hello")
assert status == 200 and '"version":"stable"' in body and '"xff":"127.0.0.1"' in body
time.sleep(1.2) # 等限流桶恢复
status, body = get(gateway, "/api/hello", {"Cookie": "canary=1"})
assert '"version":"canary"' in body
def test_sse_not_buffered(gateway):
c = http.client.HTTPConnection("127.0.0.1", gateway, timeout=5)
start = time.monotonic()
c.request("GET", "/ai/stream")
r = c.getresponse()
first = r.readline() # 读到第一条事件就返回
first_at = time.monotonic() - start
rest = r.read()
total = time.monotonic() - start
c.close()
assert first.startswith(b"data: token0")
assert b"token2" in rest
# 不缓冲时,第一条事件远早于整个响应结束(后端共耗时约 0.9 秒)
assert first_at < 0.5 < total, (first_at, total)
def test_rate_limit(gateway):
time.sleep(1.5)
codes = [get(gateway, "/api/hello")[0] for _ in range(20)]
assert codes.count(200) >= 5 and 429 in codes, codes
+30 -3
View File
@@ -4,12 +4,39 @@ title: Nginx
type: index
domain: devops
stack: [nginx]
tags: []
tags: [Nginx, 反向代理, HTTPS, 负载均衡, SSE]
week: [3, 7, 14]
---
# Nginx
反向代理、静态资源、HTTPS、SSE / WebSocket、限流、灰度。
前端出身的你对 Nginx 应该不陌生(部署 SPA、配置代理)。转后端 / AI 应用后要再往前走一步:反向代理和负载均衡、HTTPS、**大模型流式输出(SSE)的代理配置**、限流、灰度发布,以及常见 502/504 问题的排查。
> 本专题建设中:课程、企业场景、面试题和示例代码会陆续补充。
## 学习路线
| 顺序 | 课程 | 级别 | 预计 |
| --- | --- | --- | --- |
| 1 | [反向代理、负载均衡和静态资源:location 匹配、proxy_pass、SPA 回退](01-proxy-static.md) | 基础 | 2 小时 |
| 2 | [HTTPS、SSE / WebSocket、限流和灰度](02-https-stream-limit.md) | 进阶 | 3 小时 |
## 企业场景
- [AI 应用网关:流式输出不卡顿、按用户灰度新版本](scenarios/ai-gateway-sse-canary.md)
## 面试题
- [Nginx 面试题](interview.md)
## 示例代码
- [examples/gateway](examples/gateway/):网关配置模板 + pytest 测试,用真实 Nginx 验证反向代理、SPA 回退、SSE 不缓冲、限流、Cookie 灰度(本机没有 nginx 时测试自动跳过)
## 在 16 周计划中
- [第 3 周:项目一部署](../../../plan/week03-project1.md)、[第 7 周:前端部署](../../../plan/week07-frontend.md)、[第 14 周:部署](../../../plan/week14-backend-extend-deploy.md)
## 官方资料
- Nginx 文档:https://nginx.org/en/docs/
- 代理模块参数:https://nginx.org/en/docs/http/ngx_http_proxy_module.html
- 限流模块:https://nginx.org/en/docs/http/ngx_http_limit_req_module.html
+59
View File
@@ -0,0 +1,59 @@
---
id: devops.nginx.interview
title: Nginx 面试题
type: interview
domain: devops
stack: [nginx]
tags: [Nginx, 反向代理, 负载均衡, 面试]
level: basic
related: [devops.nginx.proxy-static, devops.nginx.https-stream-limit]
week: [7, 14, 16]
---
# Nginx 面试题
## 基础
### 【基础】正向代理和反向代理的区别?
**参考答案**:正向代理代表客户端访问外部服务器,服务器看到的是代理(例如公司上网代理);反向代理代表服务器接收客户端请求,客户端看到的是代理,不知道后端有哪些服务器。Nginx 常用作反向代理,做负载均衡、TLS 终止、静态资源、限流。
### 【基础】Nginx 的负载均衡策略有哪些?
**参考答案**:轮询(默认)、加权轮询(`weight`)、最少连接(`least_conn`)、IP 哈希(`ip_hash`,同一客户端固定到同一后端)、通用哈希(`hash $key`,可配合一致性哈希)。通过 `max_fails`、`fail_timeout` 做被动健康检查。
### 【基础】location 的匹配优先级是怎样的?
**参考答案**:先看 `=` 精确匹配;再找最长前缀匹配,如果它带 `^~` 就直接使用;否则按顺序匹配正则(`~`、`~*`),第一个匹配的生效;没有正则匹配就用最长前缀匹配。
### 【基础】前端单页应用部署到 Nginx 后刷新页面 404,为什么?
**参考答案**:前端路由(history 模式)的路径在服务器上没有对应文件。用 `try_files $uri $uri/ /index.html;` 让找不到的路径都返回 index.html,交给前端路由处理。
## 进阶
### 【进阶】502 和 504 有什么区别?分别怎么排查?
**参考答案**:502 Bad Gateway 是 Nginx 连接后端失败或后端返回了无效响应——后端没启动、端口错、进程崩溃、连接被拒绝,看 Nginx 错误日志里的 `connect() failed` 等信息。504 Gateway Timeout 是后端在超时时间内没有响应——后端处理慢(慢查询、调用外部服务卡住),或者 `proxy_read_timeout` 设置太短(例如大模型长回答)。
### 【进阶】代理 SSE 和 WebSocket 分别要注意什么?
**参考答案**:SSE 要关闭代理缓冲(`proxy_buffering off` 或后端返回 `X-Accel-Buffering: no`),否则流式内容被攒成一大段;读超时要放宽或者后端发心跳。WebSocket 需要 `proxy_http_version 1.1` 并传递 `Upgrade` 和 `Connection` 头完成协议升级,读超时也要调大。
### 【进阶】Nginx 怎么限流?
**参考答案**:`limit_req_zone` 定义按某个 key(如 `$binary_remote_addr`)的请求速率,基于漏桶算法;`limit_req` 应用到 location,`burst` 允许排队的突发量,`nodelay` 让突发请求不排队立即处理;超出返回 `limit_req_status`(默认 503,常改为 429)。`limit_conn` 限制并发连接数。前面还有负载均衡时要用 `real_ip` 模块取真实客户端 IP。
## 场景题
### 【场景题】AI 问答的流式输出经过 Nginx 后变成一次性返回,怎么解决?
**参考答案**:Nginx 默认对代理响应做缓冲。给流式接口单独 location,设置 `proxy_buffering off`、`proxy_cache off`,HTTP/1.1 长连接,`proxy_read_timeout` 调大;后端响应头加 `X-Accel-Buffering: no`;确认 gzip 没有压缩 `text/event-stream`;如果前面还有 CDN 或云负载均衡,也要确认它们支持流式。详见[AI 应用网关场景](scenarios/ai-gateway-sse-canary.md)。
### 【场景题】要让 10% 的用户先用新版本,Nginx 怎么做?
**参考答案**:用 `split_clients` 根据用户标识(如用户 ID Cookie 或 IP)哈希出 10% 映射到新版本 upstream;或者 `upstream` 中用 `weight` 按比例分配;指定用户体验用 `map $cookie_xxx`。注意同一用户要稳定落在同一版本(按用户标识哈希,而不是随机)、新旧版本接口兼容、能一键回滚。
### 【场景题】怎么做到发版时用户无感知(不中断请求)?
**参考答案**:后端多实例滚动发布:先把一台实例从 upstream 摘除(或标记 `down`)并 reload Nginx,等它处理完存量请求后升级,再加回去,逐台进行;后端程序要支持优雅退出。Nginx 自身修改配置用 `nginx -s reload`,旧 worker 处理完已有连接再退出,不会中断请求。
@@ -0,0 +1,109 @@
---
id: devops.nginx.scenario.ai-gateway-sse-canary
title: AI 应用网关:流式输出不卡顿、按用户灰度新版本
type: scenario
domain: devops
stack: [nginx, fastapi]
tags: [SSE, 流式输出, 灰度发布, 限流, 网关]
level: intermediate
prerequisites: [devops.nginx.https-stream-limit]
est_hours: 2
related: [devops.nginx.interview, devops.docker.scenario.compose-dev-env]
week: [7, 13, 14]
---
# AI 应用网关:流式输出不卡顿、按用户灰度新版本
## 业务背景与问题
企业内部的 AI 问答助手:前端单页应用,后端 Python FastAPI 调用大模型并以 SSE 流式返回。上线后遇到三个问题:
1. 经过 Nginx 后,回答不再逐字出现,而是等十几秒后整段出现;长回答偶尔 504。
2. 新版本的检索策略想先给内部 20 个同事试用,没有灰度手段,只能全量发布。
3. 有人写脚本刷接口,模型调用费用突增。
## 约束
- 只有一台入口服务器上的 Nginx,不引入新的网关产品。
- 灰度要能按用户指定,也要能随时关闭。
- 正常用户的体验不能受限流影响。
## 方案设计
```mermaid
flowchart LR
B[浏览器] --> N[Nginx]
N -->|/ 静态资源| S[dist/]
N -->|/api/ 限流 + 按 Cookie 选择| ST[AI 服务 稳定版]
N -->|canary=1| CA[AI 服务 灰度版]
N -->|/ai/stream 关闭缓冲| ST
```
1. **流式**:`/ai/stream` 单独一个 location,`proxy_buffering off`、`proxy_cache off`、`proxy_read_timeout 300s`;后端每 15 秒发一条 `: ping` 心跳,防止中间设备断开空闲连接。
2. **灰度**:`map $cookie_canary $api_backend`,内部同事访问一个“加入体验”页面,由后端为其设置 `canary=1` 的 Cookie;关闭灰度只需把 map 默认值都指向稳定版并 reload。也可以用 `split_clients` 按比例放量。
3. **限流**:Nginx 按 IP 做第一道粗粒度限流(`limit_req`,返回 429);后端再按用户 / 租户做精细的配额(Redis,见 [Redis 限流](../../../backend/redis/03-lock-ratelimit.md)),并记录每个用户的模型调用量。
## 关键代码
完整配置模板和自动化测试见 [examples/gateway](../examples/gateway/):
```nginx
map $cookie_canary $api_backend {
default api_stable;
"1" api_canary;
}
location /api/ {
limit_req zone=api_limit burst=5 nodelay;
proxy_pass http://$api_backend;
}
location /ai/stream {
proxy_pass http://api_stable;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 300s;
}
```
FastAPI 端的 SSE 响应头和心跳(示意):
```python
from fastapi.responses import StreamingResponse
async def event_stream(chunks):
async for text in chunks: # chunks:大模型返回的增量文本
yield f"data: {text}\n\n"
yield "data: [DONE]\n\n"
def sse(chunks) -> StreamingResponse:
return StreamingResponse(event_stream(chunks), media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
```
测试用真实 Nginx 验证了四点:SPA 回退、反向代理并传递 `X-Forwarded-For`、带 `canary=1` Cookie 的请求进入灰度后端、SSE 第一条事件不被缓冲、超过限流返回 429。
## 取舍
| 方案 | 优点 | 缺点 |
| --- | --- | --- |
| **Nginx map / split_clients(本方案)** | 无新组件,配置简单 | 规则复杂时难维护;改规则要 reload |
| API 网关产品(APISIX、Kong 等) | 动态配置、插件丰富 | 多一套系统要运维 |
| 应用内特性开关 | 粒度最细(按功能) | 需要改代码,新旧逻辑并存 |
| Kubernetes + 服务网格 | 按权重、按头部灰度都很方便 | 需要 K8s 和网格基础设施 |
## 易错点
- 只在 `/api/` 关了缓冲,SSE 走的其实是另一个 location。
- 开了 gzip 且把 `text/event-stream` 加进 `gzip_types`,流式又被攒起来。
- `proxy_read_timeout` 理解成总时长:它是两次读之间的最大间隔,心跳能避免超时。
- 灰度 Cookie 由前端随意设置:任何人都能进灰度。应由后端校验身份后设置。
- 限流只在 Nginx 按 IP:公司出口是同一个 IP,所有同事一起被限。内部系统应按用户维度在后端限流。
## 面试怎么讲
> “AI 助手经过 Nginx 后流式输出变成整段,原因是 Nginx 默认缓冲代理响应。我给流式接口单独配了 location,关闭缓冲、放宽读超时,后端加心跳;用 map 按 Cookie 把内部同事路由到灰度版本;在 Nginx 做按 IP 的粗限流、后端按用户做配额。我还写了自动化测试,用真实 Nginx 验证第一条事件不被缓冲、灰度和限流生效。”