nginx https连接池优化本质是协同优化客户端连接管理、upstream长连接复用与tls层资源控制三者:系统需设fs.file-max≥655360及nginx用户nofile限为65536,nginx主配置加worker_rlimit_nofile 65536;upstream中配keepalive 16~64并配合proxy_http_version 1.1和proxy_set_header connection '';tls层启用ssl_session_cache shared:ssl:10m和ssl_session_timeout 10m,且proxy_ssl_session_reuse on需以tcp复用为前提。

系统级文件描述符必须拉满
HTTPS 连接实际消耗 3~5 个文件描述符(FD):客户端 socket、日志句柄、SSL session 缓存槽、OCSP stapling 文件、证书链读取等。默认 1024 完全不够用。确认当前限制:
– 全局上限:cat /proc/sys/fs/file-max,建议 ≥ 655360
– nginx 用户限制:ulimit -n(启动 shell 环境)
– 实际生效值:cat /proc/$(pgrep nginx | head -1)/limits | grep "Max open files"
若第三项仍是 1024,说明未真正生效。需同步配置:
– /etc/security/limits.conf 添加:
nginx soft nofile 65536
nginx hard nofile 65536
– systemd 启动需额外加:
[Service]
LimitNOFILE=65536
保存后执行 systemctl daemon-reload && systemctl restart nginx
Nginx 主动接管 FD 上限
系统设了 limit,但 Nginx worker 进程未必能拿到——它必须在 fork 前显式调用 setrlimit()。在 nginx.conf 全局块(main context)中添加:
worker_rlimit_nofile 65536;
该值不能超过上一步设置的 hard nofile,否则启动失败。
这是关键一环:确保每个 worker 启动即拥有确定的 FD 配额,避免因启动环境差异导致行为漂移。
upstream 长连接池要配得准
这是真正决定“连接池”是否起效的核心。Nginx 对后端的复用能力,完全取决于 upstream keepalive 和协议协同。典型配置示例:
upstream api_backend {
server 10.0.1.10:8080;
keepalive 32;
}
注意:
– keepalive 值不是越大越好,一般设为 16~64,需匹配后端最大空闲连接数
– 必须配合:
• proxy_http_version 1.1;
• proxy_set_header Connection "";
• 后端响应头不能含 Connection: close
验证是否生效:
– ss -tan | grep :8080 | wc -l 应稳定在 keepalive 设定值附近
– 后端 access log 中连接建立频率应远低于 QPS
– 抓包看连续请求是否复用同一 TCP 四元组
TLS 层复用与性能绑定
SSL/TLS 握手开销大,必须靠会话复用(session reuse)和 CPU 亲和性压降延迟。关键配置:
– ssl_session_cache shared:SSL:10m;(至少支持数万会话)
– ssl_session_timeout 10m;
– proxy_ssl_session_reuse on;(回源 HTTPS 必开)
– worker_processes auto; + worker_cpu_affinity auto;
后者让每个 worker 绑定固定 CPU 核,保障 TLS 密钥运算缓存热度,避免跨核迁移拖慢 handshake
特别提醒:
proxy_ssl_session_reuse 依赖底层 TCP keepalive 复用,若 upstream keepalive 或 HTTP/1.1 协同失效,此选项形同虚设。











