Nginx在Debian上的性能调优可以通过多种方法实现,以下是一些关键的优化步骤和建议:
进程与连接调优:
worker_processes
:通常设置为等于服务器的CPU核心数,以充分利用硬件资源。例如,如果你的服务器有4个核心,可以将 worker_processes
设置为4。worker_connections
:每个工作进程可以同时处理的最大TCP连接数。这个值需要根据服务器的性能和内存来调整,但通常可以设置一个较高的值,如65535。长连接优化:
keepalive_timeout
:减少保持连接的超时时间,以减少不必要的连接保持。例如,keepalive_timeout 65;
。启用长连接:
keepalive_requests
和 keepalive_timeout
指令来设置长连接,减少连接建立和关闭的开销。例如,keepalive_requests 1000; keepalive_timeout 65;
。使用sendfile系统调用:
sendfile on;
以减少数据拷贝次数,提高文件传输效率。启用Gzip压缩:
gzip on;
指令启用Gzip压缩,减少传输数据量,加快页面加载速度。优化缓冲区大小:
http {
client_body_buffer_size 128k;
client_header_buffer_size 1k;
large_client_header_buffers 4 32k;
output_buffers 1 32k;
postpone_output 1460;
}
访问日志缓冲:
access_log
指令的缓冲功能,减少日志记录对性能的影响:access_log /var/log/nginx/access.log buffer= 32k flush= 300s;
限制连接数:
limit_conn
和 limit_rate
指令防止单个用户占用过多资源:limit_conn addr 10;
limit_rate 1m;
启用缓存:
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
静态资源缓存:
location ~* \.(js|css|png|webp)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
}
代理缓存(反向代理场景):
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=dynamic_cache:100m max_size=10g inactive=24h use_temp_path=off;
location /api {
proxy_cache dynamic_cache;
proxy_pass http://backend;
proxy_cache_lock on;
proxy_cache_valid 200 302 10m;
proxy_cache_use_stale error timeout updating;
}
OpenFileCache(文件描述符缓存):
open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
Gzip/Brotli压缩:
gzip on;
gzip_types text/plain application/json application/javascript;
gzip_min_length 1024;
brotli on;
HTTP/2与TLS优化:
listen 443 ssl http2;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_protocols TLSv1.3 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s;
location /login {
limit_req zone=api_limit burst=20 nodelay;
}
/etc/sysctl.conf
文件,添加或修改内核参数来优化性能,例如增加文件描述符限制、调整TCP窗口大小等。sudo sysctl -p
命令使更改生效。worker_rlimit_nofile
和系统的 ulimit -n
值一致,以支持高并发连接。top
, htop
, vmstat
, iostat
等来监控系统资源使用情况,及时发现并解决潜在的性能问题。apt-get autoremove
和 apt-get clean
命令清理不再需要的软件包和缓存。在进行任何配置更改后,建议进行性能测试以验证优化效果。