要充分发挥Nginx在高并发场景下的性能,需要从操作系统内核参数和Nginx配置两方面进行优化。以下是一些关键优化建议:
# 临时设置
ulimit -n 655350
# 永久设置(修改/etc/security/limits.conf)
* soft nofile 655350
* hard nofile 655350
# 编辑/etc/sysctl.conf添加以下内容
# 开启TCP连接复用,允许将TIME-WAIT sockets重新用于新的TCP连接
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
# 减少FIN-WAIT-2状态的超时时间
net.ipv4.tcp_fin_timeout = 30
# 增加系统同时保持TIME_WAIT的最大数量
net.ipv4.tcp_max_tw_buckets = 6000
# 增大系统文件描述符限制
fs.file-max = 655350
# 增加系统端口范围
net.ipv4.ip_local_port_range = 1024 65000
# 增大TCP缓冲区大小
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
# 增大最大连接数(包括等待accept的)
net.core.somaxconn = 65535
# 增大等待accept的队列长度
net.ipv4.tcp_max_syn_backlog = 65536
# 开启SYN cookies,防止SYN洪水攻击
net.ipv4.tcp_syncookies = 1
# 减少keepalive探测次数和时间
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 15
应用修改:
sysctl -p
worker_processes auto; # 自动设置为CPU核心数
worker_rlimit_nofile 65535; # 每个worker进程的文件描述符限制
events {
worker_connections 65535; # 每个worker进程的最大连接数
use epoll; # 使用epoll事件模型(Linux)
multi_accept on; # 一个worker进程同时接受多个连接
}
http {
sendfile on; # 启用sendfile系统调用
tcp_nopush on; # 启用TCP_CORK选项
tcp_nodelay on; # 禁用Nagle算法
keepalive_timeout 65; # 保持连接超时时间
keepalive_requests 10000; # 单个keepalive连接的最大请求数
client_header_buffer_size 4k; # 客户端请求头缓冲区大小
large_client_header_buffers 4 8k; # 大型请求头缓冲区
client_max_body_size 8m; # 客户端请求体最大大小
# 关闭不必要的日志记录
access_log off;
# 或者缓冲日志写入
access_log /var/log/nginx/access.log buffer=32k flush=5s;
# 开启gzip压缩
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
# 静态文件缓存
open_file_cache max=65535 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
upstream backend {
server 127.0.0.1:8080;
# 连接池大小
keepalive 32;
}
server {
location / {
proxy_pass http://backend;
# 反向代理优化
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
proxy_buffer_size 4k;
proxy_buffers 8 32k;
proxy_busy_buffers_size 64k;
}
}
worker_cpu_affinity auto;
location /video/ {
aio on;
directio 512;
output_buffers 1 128k;
}
echo 'net.core.netdev_max_backlog = 30000' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_max_syn_backlog = 8192' >> /etc/sysctl.conf
使用最新内核:Linux 4.9+内核在网络性能上有显著改进
考虑使用reuseport(Nginx 1.9.1+):
events {
accept_mutex off;
reuseport on;
}
nginx -t
测试配置是否正确top
/htop
查看CPU和内存使用ss -s
查看socket统计netstat -ant | awk '{print $6}' | sort | uniq -c
查看连接状态分布ab
、wrk
或jmeter
进行压力测试通过以上优化,Nginx可以轻松应对数万甚至更高的并发连接请求。实际优化时应根据具体硬件配置和业务需求进行调整,并通过压力测试验证优化效果。