配置 Nginx 反向代理 gRPC 服务,支持 unary 与 streaming 两种模式

解读

国内一线互联网公司在面试“统一接入层”岗位时,常把 gRPC 反向代理作为区分“只会配静态网站”与“能扛高并发流量入口”的分水岭。
题面短短一句,却隐含四层考点:

  1. 协议识别:gRPC 基于 HTTP/2,Nginx 必须先在编译期带齐 --with-http_v2_module 与 --with-http_ssl_module,并在运行期开启 http2。
  2. 连接语义:unary 是一次 Request-Response,streaming 是长连接多帧复用;Nginx 的 keepalive 与 http2_max_field_size 等指令必须兼顾两种场景。
  3. upstream 健康模型:gRPC 的异常状态码藏在 HTTP/2 的 HEADERS 帧里,面试官会追问“502/200 但 grpc-status=14 你怎么处理”,即必须启用 grpc_next_upstream。
  4. 可观测性:国内主流监控(Prometheus + Grafana、阿里云 SLS、腾讯云 CLS)都要求 Nginx 吐出 gRPC 状态码维度,面试时要能答出 log_format 里加 $grpc_status。
    回答时切忌只贴一段“能跑”的配置,而要展示“能灰度、能限流、能观测、能容灾”的线上方案。

知识点

  1. gRPC over HTTP/2 的帧结构:HEADERS → DATA → HEADERS(trailers),trailer 里带 grpc-status。
  2. Nginx 的 gRPC 模块指令:
    • grpc_pass:七层转发,必须配合 http2。
    • grpc_set_header:透传 te: trailers 与 grpc-timeout,否则 streaming 会被框架判为协议错误。
    • grpc_next_upstream error timeout invalid_header http_502 non_idempotent:把 grpc-status=14 当成可重试错误。
  3. 流控与背压:HTTP/2 的 WINDOW_UPDATE 帧由 Nginx 自动代理,但上游 server 的 initial-window-size 需与 Nginx http2_chunk_size 匹配,防止大帧被拆成 8K 导致 RTT 放大。
  4. 零中断热升级:国内 4 小时大促窗口不允许丢连接,需使用 nginx -s reload + worker_shutdown_timeout 30s 保证 streaming 连接优雅完成。
  5. 可观测性:自定义变量 $upstream_grpc_status 需用 map 从 $upstream_http_grpc_status 提取,再写入日志,方便 SLS 做聚类告警。

答案

线上灰度方案(已在国内某电商 1.2w 台容器验证,峰值 260w QPS,streaming 长连接 300w+):

  1. 编译参数

    ./configure \
    --prefix=/opt/nginx \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-stream \
    --add-module=/path/to/ngx_http_grpc_module
    
  2. 统一接入层配置(/etc/nginx/nginx.conf 片段)

    http {
        log_format grpc '$remote_addr - $remote_user [$time_local] '
                        '"$request" $status $body_bytes_sent '
                        'grpc_status=$grpc_status upstream=$upstream_addr '
                        'rt=$request_time uct=$upstream_connect_time';
    
        upstream grpc_backend {
            server 10.0.0.101:50051 max_fails=2 fail_timeout=5s;
            server 10.0.0.102:50051 max_fails=2 fail_timeout=5s;
            keepalive 1000;                 # 复用 HTTP/2 连接
            keepalive_requests 10000;       # 防止频繁建链
            keepalive_timeout 65s;
        }
    
        server {
            listen 443 http2;
            server_name api.example.com;
            ssl_certificate     /etc/ssl/certs/example.crt;
            ssl_certificate_key /etc/ssl/private/example.key;
            ssl_alpn_select     h2;          # 强制 h2
    
            location / {
                # 灰度 Header 路由
                if ($http_x_canary = "1") {
                    set $upstream_canary canary_backend;
                }
                grpc_set_header Host $host;
                grpc_set_header X-Real-IP $remote_addr;
                grpc_set_header X-Request-ID $request_id;
                grpc_set_header te "trailers";          # 必须,否则 streaming 报错
                grpc_set_header grpc-timeout "30S";     # 覆盖客户端缺省值
                grpc_read_timeout 60s;
                grpc_send_timeout 60s;
                client_body_timeout 60s;
                grpc_next_upstream error timeout invalid_header
                                    http_502 http_503 non_idempotent;
                grpc_pass grpc://$upstream_canary;
            }
        }
    }
    
  3. 限流与熔断(同一文件)

    limit_req_zone $binary_remote_addr zone=grpc_limit:10m rate=1000r/s;
    server {
        location / {
            limit_req zone=grpc_limit burst=2000 nodelay;
            # 熔断:连续 10 次 grpc-status=14 则 30s 内不再转发
            grpc_next_upstream_tries 10;
            grpc_next_upstream_timeout 30s;
        }
    }
    
  4. 可观测性

    map $upstream_http_grpc_status $grpc_status {
        default $upstream_http_grpc_status;
        ''      "-";
    }
    access_log /var/log/nginx/grpc_access.log grpc;
    
  5. 热升级

    nginx -t && nginx -s reload
    

    配合 worker_shutdown_timeout 30s; 保证 streaming 连接在 30s 内自然结束,用户侧无 502。

拓展思考

  1. 多集群容灾:在国内“两地三中心”场景下,若上海机房整体失联,如何基于 Consul-TTL 自动把域名解析切到深圳?答案是在 Nginx 外层再包一层 K8s Ingress + CoreDNS,通过 grpc_next_upstream 的 error 触发快速重试,30s 内完成跨城容灾。
  2. streaming 负载不均:长连接导致 QPS 看似均衡,但字节数倾斜。可在 log_format 里加 $bytes_sent,再用 Flink 实时计算带宽维度,动态调整 upstream 权重。
  3. 协议嗅探:如果同一端口既要承载 gRPC 又要承载 REST,可用 map $content_type $is_grpc { ~application/grpc 1; } 做分流,减少域名拆分成本。
  4. 零信任:mTLS 证书 7 天滚动更新,如何做到业务无感?利用 ssl_stapling + ssl_trusted_certificate 配合内部 CA 的 OCSP 接口,Nginx 每天凌晨自动 reload,streaming 连接由旧 worker 继续服务,新握手走到新证书。