在 Debian 上提升 Nginx 并发连接的可落地方案
一 核心原理与上限估算
二 Nginx 关键配置
# 主进程与文件句柄
worker_processes auto; # 一般设为 CPU 核心数
worker_rlimit_nofile 65535; # 提升 worker 可打开文件数(含 socket)
events {
use epoll; # Linux 高并发推荐 epoll
worker_connections 16384; # 单 worker 并发连接上限(逐步调大)
multi_accept on; # 一次接受多个新连接
}
http {
sendfile on;
tcp_nopush on; # 与 sendfile 配合,提高传输效率
tcp_nodelay on; # 减少小包排队,降低延迟
# 客户端长连接
keepalive_timeout 60s; # 保持连接超时
keepalive_requests 1000; # 单长连接可处理的请求数
# 压缩(降低带宽占用,提高吞吐)
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/javascript application/json text/xml;
gzip_vary on;
# 静态资源缓存控制(减少后端压力)
expires 1y;
add_header Cache-Control "public, immutable";
# 反向代理长连接(到 upstream)
upstream backend {
server 10.0.0.11:8080;
server 10.0.0.12:8080;
keepalive 300; # 与后端保持的长连接池大小
}
server {
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection ""; # 复用 upstream keepalive
}
# 运行状态页(仅内网访问)
location = /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}
}
三 操作系统与网络调优
www-data soft nofile 65535
www-data hard nofile 65535
LimitNOFILE=65535
systemctl daemon-reload && systemctl restart nginxnet.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.core.netdev_max_backlog = 262144
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_syncookies = 1
# 如内核版本较旧且未启用时间戳,可考虑关闭;新内核通常保持开启
# net.ipv4.tcp_timestamps = 0
sysctl -p四 监控与验证
curl http://127.0.0.1/nginx_status(关注 Active connections / accepts / handled / requests)tail -f /var/log/nginx/access.log /var/log/nginx/error.logngxtop(按状态、URI、IP 聚合,定位热点与异常)五 常见陷阱与建议