在 Debian 上优化 Nginx,通常可以从系统层面、Nginx 配置层面、安全与缓存、监控几个方向来做。下面给你一套比较实用、可落地的优化方案(适用于生产环境)。
编辑 /etc/sysctl.conf 或新建 /etc/sysctl.d/nginx.conf:
# 提高文件描述符
fs.file-max = 1000000
# TCP 优化
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 60
# 内存相关
net.ipv4.tcp_mem = 786432 2097152 3145728
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 10000;
client_body_buffer_size 128k;
client_max_body_size 20m;
client_header_buffer_size 4k;
large_client_header_buffers 4 32k;
server_tokens off;
gzip on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
gzip_vary on;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff2)$ {
expires 30d;
access_log off;
add_header Cache-Control "public";
}
open_file_cache max=100000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m max_size=1g inactive=60m;
proxy_temp_path /var/tmp/nginx;
location / {
proxy_pass http://backend;
proxy_cache mycache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
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_connect_timeout 5s;
proxy_read_timeout 30s;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
}
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options SAMEORIGIN;
limit_req_zone $binary_remote_addr zone=req_zone:10m rate=10r/s;
server {
limit_req zone=req_zone burst=20 nodelay;
}
nginx -t
systemctl reload nginx
location /nginx_status {
stub_status on;
allow 127.0.0.1;
deny all;
}
access_log off; # 高并发静态资源
# 或
access_log /var/log/nginx/access.log main buffer=32k flush=5s;
apt install apache2-utils
ab -n 10000 -c 100 http://yourdomain.com/
如果你愿意,可以告诉我:
我可以给你更精准的一版配置。