CentOS 上优化 Nginx 性能的可落地方案
一 系统层优化
ulimit -n 验证)。这直接决定单机的并发连接上限。net.ipv4.ip_local_port_range = 1024 65530,执行 sysctl -p 生效,缓解高并发短连接场景的端口耗尽。net.core.somaxconn = 262144(提升 listen 队列上限)net.core.netdev_max_backlog = 262144(网卡到内核的队列)net.ipv4.tcp_max_tw_buckets = 6000(控制 TIME_WAIT 数量)net.ipv4.tcp_tw_reuse = 1、net.ipv4.tcp_tw_recycle = 1(在 NAT/负载均衡 环境下慎用 recycle)net.ipv4.tcp_syncookies = 1(抵御 SYN Flood)net.ipv4.tcp_max_orphans = 262144(孤儿套接字上限)二 Nginx 配置优化
worker_processes auto; 或设为 CPU 核心数(如 4/8),充分利用多核。worker_rlimit_nofile 65535;(与系统 nofile 限制匹配)。events { use epoll; worker_connections 65535; multi_accept on; accept_mutex on; }(Linux 优先用 epoll;worker_processes × worker_connections 为理论并发上限)。sendfile on; tcp_nopush on; tcp_nodelay on;(零拷贝与高效传输)。keepalive_timeout 60; keepalive_requests 1000;(复用连接,降低握手开销)。gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;。location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; add_header Cache-Control "public"; }。server_tokens off;(隐藏版本号)。open_file_cache max=102400 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 1;(减少 stat/open 系统调用)。proxy_connect_timeout 15s; proxy_send_timeout 60s; proxy_read_timeout 60s;(避免长阻塞)。upstream { keepalive 32; } 并在 proxy_http_version 1.1; proxy_set_header Connection ""; 配合使用。access_log off; error_log /var/log/nginx/error.log crit;(上线前评估可观测性影响)。三 示例配置片段
# /etc/nginx/nginx.conf 关键片段
worker_processes auto;
worker_rlimit_nofile 65535;
events {
use epoll;
worker_connections 65535;
multi_accept on;
accept_mutex on;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 60;
keepalive_requests 1000;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
open_file_cache max=102400 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 1;
server_tokens off;
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public";
}
# 示例:上游长连接(按需)
# upstream backend {
# server 10.0.0.11:8080;
# server 10.0.0.12:8080;
# keepalive 32;
# }
#
# server {
# location / {
# proxy_pass http://backend;
# proxy_http_version 1.1;
# proxy_set_header Connection "";
# proxy_set_header Host $host;
# proxy_set_header X-Real-IP $remote_addr;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header X-Forwarded-Proto $scheme;
# }
# }
}
上述片段覆盖了进程、连接、传输、压缩、缓存与上游长连接等关键优化点,可直接按需合并到现有配置中。
四 验证与上线
nginx -t && systemctl reload nginx,确保语法正确后再生效。ss -s、netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'、top/vmstat/iostat 观察连接、CPU、IO 与负载。ab、wrk、jmeter 或 k6 进行渐进式压测,逐步提升并发,观察 P95/P99 延迟 与 错误率,结合 error.log 与监控定位瓶颈。worker_connections 与超时,最后优化压缩/缓存与上游长连接,避免一次性大幅改动带来不稳定。