在 Debian 上优化 Nginx 性能,可以从系统层面、Nginx 配置、缓存、网络和安全几个方向入手。下面是一套比较实用、可落地的优化方案。
编辑 /etc/sysctl.conf 或 /etc/sysctl.d/99-nginx.conf:
# 文件描述符
fs.file-max = 1000000
# TCP 队列
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
# TCP 连接复用
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15
# 内存相关
net.ipv4.tcp_rmem = 4096 87380 67108864
net.ipv4.tcp_wmem = 4096 65536 67108864
应用:
sysctl -p
/etc/security/limits.conf:
* soft nofile 1000000
* hard nofile 1000000
配置文件通常在:
/etc/nginx/nginx.conf
worker_processes auto;
worker_rlimit_nofile 100000;
events {
worker_connections 10240;
use epoll;
multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 30;
keepalive_requests 100;
}
gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$ {
expires 30d;
access_log off;
}
open_file_cache max=100000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
fastcgi_read_timeout 60s;
}
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m max_size=1g inactive=60m;
proxy_cache mycache;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_cache_use_stale error timeout updating;
}
listen 443 ssl http2;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets on;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
access_log off; # 静态资源
# 或
access_log /var/log/nginx/access.log main buffer=32k flush=5s;
nginx -T(检查配置)htop, vmstatgoaccess(日志分析)prometheus + nginx-exporterapt 旧版本:apt install nginx-full
systemd 限制:[Service]
LimitNOFILE=100000
如果你能告诉我:
我可以给你一套更精准的配置文件。