Nginx作为高性能的Web服务器和反向代理,通过合理的优化可以显著提升并发处理能力、降低资源消耗。以下是全面的优化方案,分为核心参数调优、系统层优化和架构优化三个维度:
Worker进程优化
worker_processes auto; # 自动匹配CPU核心数
worker_cpu_affinity auto; # CPU亲和性(Linux)
worker_rlimit_nofile 65535; # 每个worker能打开的文件描述符上限
连接数与事件模型
events {
worker_connections 4096; # 单个worker最大连接数
use epoll; # Linux高性能事件模型
multi_accept on; # 一次性接受所有新连接
accept_mutex off; # 高并发时关闭互斥锁
}
HTTP核心参数
http {
sendfile on; # 零拷贝传输静态文件
tcp_nopush on; # 合并数据包减少发送次数
tcp_nodelay on; # 禁用Nagle算法
keepalive_timeout 30s; # 长连接超时
keepalive_requests 1000; # 单个长连接最大请求数
server_tokens off; # 隐藏版本号
}
缓冲与超时控制
client_body_buffer_size 16k;
client_header_buffer_size 4k;
client_max_body_size 10m;
client_body_timeout 12s;
client_header_timeout 12s;
Linux内核参数调整
# /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
fs.file-max = 2097152
执行 sysctl -p
生效
文件描述符限制
# /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
网络栈优化
bash
echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf
静态资源分离
nginx
location ~* \.(jpg|css|js)$ {
expires 365d;
add_header Cache-Control "public";
}
负载均衡策略
upstream backend {
least_conn; # 最少连接算法
server 10.0.0.1:8080 weight=5;
server 10.0.0.2:8080;
keepalive 32; # 后端长连接
}
启用Gzip压缩
gzip on;
gzip_comp_level 5;
gzip_types text/plain application/xml text/css application/javascript;
日志优化
nginx
access_log /var/log/nginx/access.log combined buffer=32k flush=5m;
启用HTTP/2
listen 443 ssl http2; # 需同时配置SSL证书
实时监控工具
nginx -t # 配置检查
nginx -T # 查看完整配置
htop # 系统资源监控
ss -lntp | grep nginx # 查看连接状态
日志分析
tail -f /var/log/nginx/error.log
压力测试
ab -c 1000 -n 50000 http://example.com/
wrk -t4 -c1000 -d30s --latency http://example.com/
nginx
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
通过以上优化组合,Nginx可轻松支持万级并发(单机2C4G配置实测可达8000+ QPS)。建议根据实际业务场景进行参数微调,并通过压测工具验证效果。对于超大规模场景,可考虑LVS+Nginx的多级负载架构。