在 Linux 上优化 Nginx,通常从系统层面、Nginx 配置、缓存、安全与监控几个方面入手。下面给你一份比较实用、可落地的优化清单。
Nginx 高并发时会吃 fd
# 查看
ulimit -n
# 修改(永久)
/etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
net.core.somaxconn = 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
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;
events {
use epoll;
worker_connections 65535;
multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 1000;
}
gzip on;
gzip_min_length 1k;
gzip_comp_level 5;
gzip_types text/plain text/css application/json application/javascript;
location ~* \.(jpg|css|js|png)$ {
expires 30d;
access_log off;
}
limit_conn_zone $binary_remote_addr zone=conn:10m;
limit_conn conn 100;
limit_req_zone $binary_remote_addr zone=req:10m rate=10r/s;
limit_req zone=req burst=20 nodelay;
upstream backend {
server 127.0.0.1:8080;
keepalive 32;
}
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_read_timeout 60s;
}
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=mycache:10m max_size=1g;
location / {
proxy_cache mycache;
proxy_cache_valid 200 10m;
}
server_tokens off;
add_header X-Frame-Options SAMEORIGIN;
client_max_body_size 10m;
location /nginx_status {
stub_status on;
allow 127.0.0.1;
deny all;
}
ab -n 10000 -c 100 http://ip/
wrk -t4 -c100 -d30s http://ip/
❌ 盲目调大 worker_connections
❌ 不区分静态/动态请求
❌ 不开缓存就上高并发
❌ 忽视 Linux 内核参数
如果你愿意,可以告诉我:
我可以直接给你一套可直接用的 nginx.conf。