在 Debian 上提升 Nginx 并发能力的核心思路是:让 Nginx 能打开足够多的文件描述符与连接、使用高效的事件模型、减少连接与传输开销,并通过缓存与负载均衡降低后端压力。下面给出可直接落地的配置与系统调优步骤。
一 系统层调优
* soft nofile 65535
* hard nofile 65535
worker_rlimit_nofile 65535;
ulimit -n 与 ps aux --no-headers | grep nginx | wc -l 校验。fs.file-max = 2097152
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_syncookies = 1
sudo sysctl -p二 Nginx 关键配置
auto),并为每个进程配置充足的 worker_connections;在 events 中使用 epoll、开启 multi_accept 提升事件处理效率:worker_processes auto;
worker_rlimit_nofile 65535;
events {
use epoll;
worker_connections 65535;
multi_accept on;
}
http {
keepalive_timeout 65;
keepalive_requests 1000;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
}
http {
gzip on;
gzip_vary on;
gzip_min_length 10240;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_pass http://backend;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
}
}
}
http {
client_body_timeout 10s;
client_header_timeout 10s;
send_timeout 15s;
client_body_buffer_size 16k;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
client_max_body_size 20M;
}
upstream backend {
least_conn;
server 10.0.0.11:8080;
server 10.0.0.12:8080;
}
server {
location / {
proxy_pass http://backend;
}
}
三 验证与监控
sudo nginx -tsudo systemctl reload nginxss -s、netstat -n | grep :80 | wc -l、ps aux --no-headers | grep nginx | wc -ltop、htop、vmstat 1/var/log/nginx/access.log、/var/log/nginx/error.log,必要时接入 Prometheus + Grafana(如 nginx-prometheus-exporter)做可视化监控与告警。四 安全与合规建议
http {
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server {
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
}
location /admin/ {
allow 192.168.1.0/24;
deny all;
}
}
}