在 Debian 上优化 Nginx 性能,通常可以从系统层、Nginx 配置层、以及架构层三个方面来做。下面给你一套比较实用、可落地的优化方案。
Nginx 高并发时容易受限于 fd 数量。
# 查看当前限制
ulimit -n
# 修改系统限制
vim /etc/security/limits.conf
添加:
* soft nofile 65535
* hard nofile 65535
# 修改 systemd 限制
vim /etc/systemd/system/nginx.service.d/limits.conf
[Service]
LimitNOFILE=65535
systemctl daemon-reload
systemctl restart nginx
编辑 /etc/sysctl.conf:
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 = 600
应用:
sysctl -p
如果是静态资源服务器:
defaults,noatime
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;
events {
use epoll;
worker_connections 10240;
multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 10000;
client_body_buffer_size 128k;
client_header_buffer_size 4k;
large_client_header_buffers 4 16k;
server_tokens off;
}
gzip on;
gzip_min_length 1k;
gzip_comp_level 5;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
gzip_vary on;
location ~* \.(jpg|jpeg|png|gif|css|js|ico|woff2)$ {
expires 30d;
access_log off;
}
open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m max_size=1g inactive=60m;
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_send_timeout 10s;
proxy_read_timeout 10s;
}
fastcgi_cache_path /var/cache/nginx/fcgi levels=1:2 keys_zone=phpcache:10m;
fastcgi_cache phpcache;
fastcgi_cache_valid 200 5m;
并调整:
vim /etc/php/*/fpm/pool.d/www.conf
pm = dynamic
pm.max_children = 100
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
listen 443 ssl http2;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ngx_brotlingx_pagespeednginx-module-vts(监控)# 压测
ab -n 100000 -c 1000 http://yourdomain/
# 查看状态
nginx -T
ss -ant | wc -l
如果你愿意,可以告诉我:
我可以给你一套更精准的 Debian + Nginx 配置模板。