Nginx作为高性能的Web服务器和反向代理,其性能优化需要从多维度进行调优。以下是一套系统化的优化方案,分为核心参数、系统层、架构层和高级技巧四个部分:
worker_processes auto; # 自动匹配CPU核心数
worker_cpu_affinity auto; # CPU亲和性(Nginx 1.9.10+)
worker_rlimit_nofile 100000; # worker进程最大打开文件数
events {
worker_connections 4096; # 每个worker的最大连接数
use epoll; # Linux内核使用epoll事件模型
multi_accept on; # 一次性接受所有新连接
}
http {
# 缓冲优化
client_body_buffer_size 10K;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
# 超时控制
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
# TCP优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 静态文件优化
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
文件描述符限制
# 修改系统限制
echo "* soft nofile 1000000" >> /etc/security/limits.conf
echo "* hard nofile 1000000" >> /etc/security/limits.conf
ulimit -n 1000000
内核参数优化(/etc/sysctl.conf)
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65536
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.ip_local_port_range = 1024 65000
fs.file-max = 1000000
sysctl -p
生效
禁用SWAP(内存充足时)
swapoff -a && sysctl vm.swappiness=0
动静分离
location ~* \.(jpg|css|js)$ {
expires 30d;
access_log off;
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; # 保持长连接
}
启用HTTP/2
listen 443 ssl http2;
动态模块按需加载
./configure --with-http_image_filter_module=dynamic
日志优化
log_format compression '$remote_addr - $request_time $body_bytes_sent';
Zero-Copy技术(Linux 4.14+)
sendfile on;
sendfile_max_chunk 512k;
内存池优化(适用于高并发)
server {
request_pool_size 4k;
}
实时监控工具
nginx -T # 检查配置
nginx -V # 查看编译参数
ss -lntp | grep nginx # 查看连接状态
压测工具验证
ab -c 1000 -n 100000 http://test.com/
wrk -t4 -c1000 -d30s --latency http://test.com/
worker_connections
和open_file_cache
proxy_buffer_size
和proxy_busy_buffers_size
通过以上优化组合,Nginx在4核8G标准服务器上可轻松应对5万+的并发连接(需配合应用层优化)。建议每次修改后通过压测工具验证效果,避免过度优化。