Ubuntu上Nginx性能优化实操指南
一 基线测量与压测方法
ab -c 40 -n 50000 http://你的域名/,记录结果以便与调优后对比。每次只做少量变更并回归测试,确保收益可量化。二 系统层优化
* soft nofile 65535
* hard nofile 65535
root soft nofile 65535
root hard nofile 65535
确保登录会话与 systemd 服务均能继承该上限(必要时在 systemd 服务单元中设置 LimitNOFILE=)。/etc/sysctl.d/99-nginx-performance.conf,示例:net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
# 注意:在 Nginx 作为反向代理且后端同为 NAT/负载均衡时,谨慎开启 tcp_tw_recycle
应用:sudo sysctl -p。这些参数增大套接字缓冲区、加速 TIME_WAIT 回收,有助于高并发下的吞吐与稳定性。三 Nginx核心配置优化
worker_processes auto;(通常设为 CPU 核心数,充分利用多核)worker_connections 10240;(结合业务与文件描述符上限逐步调大)sendfile on;(零拷贝传输静态文件)gzip on; gzip_comp_level 5; gzip_min_length 256; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; gzip_vary on;keepalive_timeout 65; keepalive_requests 100;(在反向代理与静态资源场景提升复用率)location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
add_header Cache-Control "public, immutable";
}
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_pass http://backend;
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;
}
}
fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=fcgi:10m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_cache_valid 200 302 10m;
fastcgi_cache_valid 404 1m;
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;
server {
location / {
limit_req zone=mylimit burst=5 nodelay;
}
}
listen 443 ssl http2;,可显著降低连接开销、提升并发加载性能。四 安全与传输层优化
五 监控验证与持续迭代