Gin 如何配置 Nginx 保持长连接?
解读
面试官问“Gin 如何配置 Nginx 保持长连接”,并不是想听你背 Nginx 参数,而是考察三点:
- 是否意识到“长连接”是端到端行为:浏览器 ↔ Nginx ↔ Gin(Go)。
- 能否把 Nginx 的 keep-alive 与 Go 的 HTTP Server 参数联动起来,避免“半开连接”或 502。
- 是否具备线上调优经验:内核参数、超时、单连接最大请求数、优雅退出。
在国内云原生场景下,Nginx 多数以 Ingress 或反向代理形态出现,答“只改 keepalive_timeout”会被判为不及格。
知识点
-
Nginx 侧
upstream keepalive 指令:复用到 Gin 的 TCP 连接池,减少三次握手。
keepalive_timeout / keepalive_requests:控制单 TCP 连接的空闲时长与最大复用次数。
proxy_http_version 1.1; proxy_set_header Connection “”; 强制使用 HTTP/1.1 并清除 close 头。 -
Gin(Go)侧
http.Server.ReadTimeout / WriteTimeout / IdleTimeout:必须 ≥ Nginx 的 keepalive_timeout,否则 Nginx 先关连接,Gin 还在写,触发 “write: broken pipe”。
优雅重启:利用 gin.CustomHTTPServer 结合 fvbock/endless 或 k8s preStop sleep,确保旧连接处理完再退出。 -
操作系统
net.ipv4.tcp_keepalive_time / probes / intvl:防止 NAT 防火墙静默丢弃空闲连接。
ulimit -n:云主机默认 1024,高并发需调大。 -
链路验证
使用 ss -o state established | grep :80 观察连接复用率;
wrk -c 200 -d 30s -H “Connection: keep-alive” 压测,对比 QPS、RT、TIME_WAIT 数量。
答案
线上标准做法分四步,可直接写进简历。
第一步:Nginx upstream 打开长连接池
http {
upstream gin_backend {
server 127.0.0.1:9000 max_fails=3 fail_timeout=10s;
keepalive 512; # 池子里最多 512 条空闲连接
keepalive_timeout 60s; # 空闲 60 秒回收
keepalive_requests 10000; # 单连接最多复用 1 万次
}
server {
listen 80;
location / {
proxy_pass http://gin_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_connect_timeout 3s;
proxy_send_timeout 10s;
proxy_read_timeout 60s; # 与 Gin 的 IdleTimeout 对齐
}
}
}
第二步:Gin 启动参数对齐
router := gin.New()
srv := &http.Server{
Addr: ":9000",
Handler: router,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 65 * time.Second, // 略大于 Nginx 的 60s,防止抢先关闭
MaxHeaderBytes: 1 << 20,
}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen err: %v", err)
}
}()
第三步:操作系统调优(/etc/sysctl.conf)
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl = 30
net.core.somaxconn = 65535
fs.file-max = 1000000
执行 sysctl -p 生效。
第四步:发布时优雅重启
使用 kubernetes:
lifecycle:
preStop:
exec:
command: ["/bin/sh","-c","sleep 15"]
terminationGracePeriodSeconds: 30
或使用 endless 库:
router := gin.Default()
endless.ListenAndServe(":9000", router)
保证旧连接处理完再退出,防止 502。
完成以上四步,wrk 复用长连接压测,QPS 可提升 25% 以上,TIME_WAIT 降低 90%,符合国内高并发面试“可落地”标准。
拓展思考
- HTTP/2 场景:Nginx 1.9.5+ 支持 h2,但 upstream 仍走 HTTP/1.1,若 Gin 也开启 h2c(cleartext HTTP/2),需要 go1.20+ 的 http2.ConfigureServer,并确认 Nginx 的 proxy_http_version 保持 1.1,避免协议混用。
- 服务网格 sidecar:Istio/Envoy 默认已做连接池,若再配 Nginx Ingress,需把 Envoy 的 max_requests_per_connection 与 Nginx 的 keepalive_requests 调成倍数关系,否则会出现“连接刚复用就被 Envoy 强制断开”。
- 指标观测:Prometheus + grafana 面板重点看 nginx_upstream_keepalive_connections 与 go_http_handled_seconds_bucket,若前者持续为 0,说明 keepalive 未生效;若后者 P99 突增,可能是 IdleTimeout 过短导致频繁新建连接。