在高并发与网络高抖动环境下,默认的 Nginx 配置往往受限于操作系统的 FD 上限与低效的 TCP 三次握手过程。本文针对内核参数调优、连接池复用与静态资源处理进行深度落地。

一、 Linux 内核网络栈参数配套调优 (/etc/sysctl.conf)

修改内核参数以提升半连接队列容量并开启 TIME_WAIT 套接字复用:

# 增大系统最大句柄数
fs.file-max = 2097152

# 增大连接套接字队列上限
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535

# 快速回收与复用 TIME_WAIT 套接字
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15

# 动态缓冲区自动调优
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216

二、 主配置文件核心优化 (nginx.conf)

user www-data;
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;

events {
    use epoll;
    worker_connections 65535;
    multi_accept on;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    # 高效传输机制
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;

    # 连接超时管理
    keepalive_timeout  65;
    keepalive_requests 10000;
    reset_timedout_connection on;
    client_body_timeout 10;
    send_timeout 10;

    # Open File Cache 句柄缓存
    open_file_cache max=65535 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # Gzip 压缩策略
    gzip on;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_proxied any;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml;

    include /etc/nginx/conf.d/*.conf;
}