优化 Debian 上的 Nginx,通常可以从系统层、Nginx 配置层、安全与运维层三个维度来做。下面我按“实用 + 可落地”的方式给你一份清单。
Nginx 高并发时容易遇到 too many open files
# 查看当前限制
ulimit -n
# 修改系统限制
echo "* soft nofile 65535" >> /etc/security/limits.conf
echo "* hard nofile 65535" >> /etc/security/limits.conf
并使 systemd 生效:
mkdir -p /etc/systemd/system/nginx.service.d
cat > /etc/systemd/system/nginx.service.d/limits.conf <<EOF
[Service]
LimitNOFILE=65535
EOF
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 = 15
net.ipv4.ip_local_port_range = 1024 65535
生效:
sysctl -p
/etc/nginx/nginx.conf
user www-data;
worker_processes auto; # 自动匹配 CPU 核数
worker_rlimit_nofile 65535;
events {
worker_connections 10240; # 单 worker 连接数
use epoll; # Debian/Linux 推荐
multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 30;
keepalive_requests 1000;
}
gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
gzip_vary on;
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
listen 443 ssl http2;
并确保:
server_tokens off;
http {
limit_req_zone $binary_remote_addr zone=req_zone:10m rate=10r/s;
}
server {
limit_req zone=req_zone burst=20 nodelay;
}
如果是 apt 安装,可改用精简版:
apt install nginx-light
或源码编译只保留需要模块。
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;
| 项目 | 默认 | 优化后 |
|---|---|---|
| 并发连接 | 几千 | 几万+ |
| 带宽占用 | 高 | ↓ 30–60% |
| 响应延迟 | 中 | ↓ 明显 |
如果你只想快速见效:
worker_processes autoworker_connections 10240sendfile ongzip onhttp2limit_req如果你愿意,可以告诉我:
我可以直接帮你写一份可直接用的 nginx.conf。