性能优化
2026/3/20大约 8 分钟
性能优化
操作系统级优化
文件描述符限制
# 查看当前限制
ulimit -n
# 临时修改(当前会话)
ulimit -n 65535
# 永久修改
# 编辑 /etc/security/limits.conf
cat >> /etc/security/limits.conf << 'EOF'
# Nginx 用户文件描述符限制
nginx soft nofile 65535
nginx hard nofile 65535
* soft nofile 65535
* hard nofile 65535
# 进程数限制
nginx soft nproc 65535
nginx hard nproc 65535
EOF
# 编辑 /etc/pam.d/common-session(Ubuntu)
echo "session required pam_limits.so" >> /etc/pam.d/common-session
# 编辑 systemd 服务文件
# /etc/systemd/system/nginx.service.d/override.conf
[Service]
LimitNOFILE=65535
LimitNPROC=65535
内核参数调优
# /etc/sysctl.conf
# === 网络参数 ===
# 最大连接队列长度
net.core.somaxconn = 65535
# 网络设备接收队列长度
net.core.netdev_max_backlog = 65535
# 系统最大文件描述符
fs.file-max = 1000000
# === TCP 参数 ===
# 允许 TIME_WAIT 状态的 socket 重用
net.ipv4.tcp_tw_reuse = 1
# TIME_WAIT 超时时间
net.ipv4.tcp_fin_timeout = 15
# TCP keepalive 时间
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl = 15
# 半连接队列长度
net.ipv4.tcp_max_syn_backlog = 65535
# 本地端口范围
net.ipv4.ip_local_port_range = 1024 65535
# TCP 内存
net.ipv4.tcp_mem = 786432 1048576 1572864
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
# 核心读写缓冲区
net.core.rmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_default = 262144
net.core.wmem_max = 16777216
# TCP 快速打开
net.ipv4.tcp_fastopen = 3
# 启用 SYN Cookie(防止 SYN 洪水)
net.ipv4.tcp_syncookies = 1
# 最大 TIME_WAIT 数量
net.ipv4.tcp_max_tw_buckets = 262144
# 禁用慢启动重启
net.ipv4.tcp_slow_start_after_idle = 0
# 应用配置
sudo sysctl -p
网络优化参数说明
| 参数 | 推荐值 | 说明 |
|---|---|---|
net.core.somaxconn | 65535 | 监听队列最大长度 |
net.core.netdev_max_backlog | 65535 | 网卡接收队列长度 |
net.ipv4.tcp_tw_reuse | 1 | 复用 TIME_WAIT 连接 |
net.ipv4.tcp_fin_timeout | 15 | FIN 超时时间(秒) |
net.ipv4.tcp_max_syn_backlog | 65535 | SYN 队列长度 |
net.ipv4.ip_local_port_range | 1024 65535 | 可用端口范围 |
fs.file-max | 1000000 | 系统最大文件句柄数 |
Nginx 进程优化
worker_processes 设置
# 自动检测 CPU 核心数(推荐)
worker_processes auto;
# 手动指定(等于 CPU 核心数)
worker_processes 4;
# 查看 CPU 核心数
# grep processor /proc/cpuinfo | wc -l
# 或
# nproc
worker_connections 计算
events {
# 单个 Worker 最大连接数
worker_connections 65535;
# 使用 epoll(Linux)
use epoll;
# 接受多个新连接
multi_accept on;
}
最大并发计算:
| 场景 | 计算公式 |
|---|---|
| 静态服务器 | worker_processes × worker_connections |
| 反向代理 | worker_processes × worker_connections / 2 |
| 代理+长连接 | worker_processes × worker_connections / 4 |
CPU 绑定与优先级
# 4 核 CPU:每个 Worker 绑定一个核心
worker_cpu_affinity 0001 0010 0100 1000;
# 8 核 CPU
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
# 自动绑定(1.9.10+)
worker_cpu_affinity auto;
# Worker 进程优先级(-20 到 20)
worker_priority -10;
# 单个 Worker 最大打开文件数
worker_rlimit_nofile 65535;
完整进程配置
# 运行用户
user nginx;
# Worker 进程数
worker_processes auto;
# CPU 绑定
worker_cpu_affinity auto;
# 进程优先级
worker_priority -10;
# 文件描述符限制
worker_rlimit_nofile 65535;
# PID 文件
pid /run/nginx.pid;
# 错误日志
error_log /var/log/nginx/error.log warn;
events {
worker_connections 65535;
use epoll;
multi_accept on;
accept_mutex off;
}
网络传输优化
sendfile 与 TCP 优化
http {
# 开启高效文件传输(零拷贝)
sendfile on;
# 配合 sendfile 使用
# 等待数据包填满后再发送
tcp_nopush on;
# 禁用 Nagle 算法
# 小数据包立即发送
tcp_nodelay on;
# aio(异步 I/O)
aio on;
# 或使用线程池
aio threads;
# 直接 I/O(大文件)
directio 4m;
directio_alignment 512;
}
keepalive 连接优化
http {
# 客户端 keepalive 超时
keepalive_timeout 65s;
# 单个 keepalive 连接最大请求数
keepalive_requests 10000;
# 禁用关闭时等待
reset_timedout_connection on;
# upstream keepalive
upstream backend {
server 127.0.0.1:8080;
# 保持的空闲连接数
keepalive 32;
# keepalive 超时
keepalive_timeout 60s;
# 每个连接最大请求数
keepalive_requests 1000;
}
server {
location / {
proxy_pass http://backend;
# 启用 HTTP/1.1
proxy_http_version 1.1;
# 清空 Connection 头
proxy_set_header Connection "";
}
}
}
缓冲区优化
http {
# === 客户端缓冲区 ===
# 请求头缓冲区
client_header_buffer_size 1k;
# 大请求头缓冲区
large_client_header_buffers 4 8k;
# 请求体缓冲区
client_body_buffer_size 128k;
# 最大请求体大小
client_max_body_size 100m;
# === 代理缓冲区 ===
# 代理响应头缓冲区
proxy_buffer_size 4k;
# 代理响应体缓冲区
proxy_buffers 8 32k;
# 高负载缓冲区
proxy_busy_buffers_size 64k;
# 临时文件最大大小
proxy_max_temp_file_size 1024m;
# === FastCGI 缓冲区 ===
fastcgi_buffer_size 4k;
fastcgi_buffers 8 32k;
fastcgi_busy_buffers_size 64k;
}
压缩优化
Gzip 压缩
http {
# 开启 gzip
gzip on;
# 压缩级别(1-9)
# 建议 4-6,平衡压缩率和 CPU
gzip_comp_level 5;
# 最小压缩长度
gzip_min_length 1024;
# 压缩缓冲区
gzip_buffers 16 8k;
# 压缩的 MIME 类型
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml
application/xml+rss
application/x-javascript
image/svg+xml
font/opentype
font/ttf
font/eot
font/otf;
# Vary 头
gzip_vary on;
# 代理请求压缩
gzip_proxied any;
# 禁用 IE6 压缩
gzip_disable "MSIE [1-6]\.";
# HTTP 版本
gzip_http_version 1.1;
}
Gzip 预压缩
http {
# 需要 ngx_http_gzip_static_module
# 优先发送预压缩文件
gzip_static on;
# 同时开启动态压缩作为回退
gzip on;
}
生成预压缩文件:
# 压缩所有 JS 和 CSS 文件
find /var/www/html -type f \( -name "*.js" -o -name "*.css" \) -exec gzip -9 -k {} \;
# 使用 zopfli(更好的压缩率)
find /var/www/html -type f \( -name "*.js" -o -name "*.css" \) -exec zopfli {} \;
Brotli 压缩
# 需要安装 ngx_brotli 模块
http {
# 动态 Brotli 压缩
brotli on;
brotli_comp_level 6;
brotli_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml
image/svg+xml;
# 预压缩
brotli_static on;
# 同时保留 gzip 作为回退
gzip on;
}
缓存优化
浏览器缓存
server {
# 静态资源长期缓存
location ~* \.(jpg|jpeg|png|gif|ico|webp|svg)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
location ~* \.(css|js)$ {
expires 7d;
add_header Cache-Control "public";
access_log off;
}
location ~* \.(woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
add_header Access-Control-Allow-Origin *;
}
}
文件描述符缓存
http {
# 文件描述符缓存
open_file_cache max=65535 inactive=60s;
# 缓存有效性检查间隔
open_file_cache_valid 30s;
# 最小使用次数才缓存
open_file_cache_min_uses 2;
# 缓存错误信息
open_file_cache_errors on;
}
代理缓存优化
http {
proxy_cache_path /var/cache/nginx
levels=1:2
keys_zone=cache:100m
max_size=10g
inactive=7d
use_temp_path=off;
server {
location / {
proxy_pass http://backend;
proxy_cache cache;
proxy_cache_valid 200 1h;
# 缓存锁防止击穿
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
# 使用过期缓存
proxy_cache_use_stale error timeout updating;
# 后台更新
proxy_cache_background_update on;
}
}
}
连接优化
upstream keepalive
upstream backend {
server 127.0.0.1:8001;
server 127.0.0.1:8002;
# 空闲连接池大小
keepalive 100;
# 单连接最大请求数
keepalive_requests 10000;
# 空闲超时
keepalive_timeout 60s;
}
server {
location / {
proxy_pass http://backend;
# 必须使用 HTTP/1.1
proxy_http_version 1.1;
# 清除 Connection 头
proxy_set_header Connection "";
}
}
超时参数调优
http {
# === 客户端超时 ===
# 读取请求头超时
client_header_timeout 15s;
# 读取请求体超时
client_body_timeout 15s;
# 发送响应超时
send_timeout 30s;
# keepalive 超时
keepalive_timeout 65s 65s;
# === 代理超时 ===
# 连接后端超时
proxy_connect_timeout 10s;
# 读取后端响应超时
proxy_read_timeout 60s;
# 发送请求到后端超时
proxy_send_timeout 30s;
}
HTTP/2 优化
server {
listen 443 ssl http2;
# HTTP/2 推送(可选)
http2_push_preload on;
location / {
# 预加载资源
add_header Link "</css/main.css>; rel=preload; as=style";
add_header Link "</js/main.js>; rel=preload; as=script";
}
}
http {
# HTTP/2 特定优化
http2_max_concurrent_streams 128;
http2_recv_buffer_size 256k;
}
性能测试工具
ab (Apache Bench)
# 基本测试
ab -n 10000 -c 100 http://localhost/
# 参数说明
# -n: 总请求数
# -c: 并发数
# -k: 启用 keepalive
# -H: 添加请求头
# 带 keepalive 测试
ab -n 10000 -c 100 -k http://localhost/
# 测试 POST 请求
ab -n 1000 -c 50 -p data.json -T application/json http://localhost/api/
wrk
# 安装
git clone https://github.com/wg/wrk.git
cd wrk && make
# 基本测试
# -t: 线程数
# -c: 连接数
# -d: 持续时间
wrk -t12 -c400 -d30s http://localhost/
# 带 Lua 脚本
wrk -t12 -c400 -d30s -s post.lua http://localhost/api/
# 输出示例
# Running 30s test @ http://localhost/
# 12 threads and 400 connections
# Thread Stats Avg Stdev Max +/- Stdev
# Latency 1.42ms 1.00ms 50.12ms 89.32%
# Req/Sec 23.48k 2.34k 30.23k 70.12%
# 8412354 requests in 30.10s, 1.23GB read
# Requests/sec: 279517.43
# Transfer/sec: 41.81MB
siege
# 安装
yum install -y siege # CentOS
apt install -y siege # Ubuntu
# 基本测试
siege -c 100 -t 30s http://localhost/
# 从文件读取 URL 列表
siege -c 50 -t 1M -f urls.txt
# 参数说明
# -c: 并发用户数
# -t: 测试时间
# -r: 每个用户重复次数
# -b: 基准测试模式(无延迟)
性能瓶颈排查
CPU 瓶颈
# 查看 CPU 使用
top -Hp $(pgrep -f "nginx: worker")
# 使用 perf 分析
perf top -p $(pgrep -f "nginx: worker" | head -1)
# 火焰图
perf record -F 99 -p $(pgrep -f "nginx: worker" | head -1) -g -- sleep 30
perf script | ./FlameGraph/stackcollapse-perf.pl | ./FlameGraph/flamegraph.pl > nginx.svg
内存瓶颈
# 查看内存使用
ps aux | grep nginx
# 详细内存信息
cat /proc/$(pgrep -f "nginx: master")/status | grep -E "Vm|Rss"
# 使用 pmap
pmap -x $(pgrep -f "nginx: worker" | head -1)
I/O 瓶颈
# 查看磁盘 I/O
iostat -x 1
# 查看文件描述符使用
ls /proc/$(pgrep -f "nginx: worker" | head -1)/fd | wc -l
# 使用 strace 跟踪系统调用
strace -p $(pgrep -f "nginx: worker" | head -1) -c
网络瓶颈
# 查看连接状态
ss -s
# 查看 TIME_WAIT 连接数
ss -ant | awk '/TIME-WAIT/ {count++} END {print count}'
# 查看连接队列
ss -ltn | grep :80
# 查看网络带宽
iftop -i eth0
生产环境优化配置模板
# /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
worker_cpu_affinity auto;
worker_priority -10;
worker_rlimit_nofile 65535;
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
events {
worker_connections 65535;
use epoll;
multi_accept on;
accept_mutex off;
}
http {
# 基础配置
include /etc/nginx/mime.types;
default_type application/octet-stream;
charset utf-8;
# 隐藏版本号
server_tokens off;
# 日志配置
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'rt=$request_time uct="$upstream_connect_time" '
'uht="$upstream_header_time" urt="$upstream_response_time"';
access_log /var/log/nginx/access.log main buffer=32k flush=5s;
# 文件传输优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
aio on;
# 连接优化
keepalive_timeout 65;
keepalive_requests 10000;
reset_timedout_connection on;
# 超时设置
client_header_timeout 15s;
client_body_timeout 15s;
send_timeout 30s;
# 缓冲区
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
client_body_buffer_size 128k;
client_max_body_size 100m;
# Gzip 压缩
gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_vary on;
gzip_proxied any;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml
application/xml+rss image/svg+xml;
# Gzip 预压缩
gzip_static on;
# 文件缓存
open_file_cache max=65535 inactive=60s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# 代理缓存
proxy_cache_path /var/cache/nginx/proxy_cache
levels=1:2
keys_zone=proxy_cache:100m
max_size=10g
inactive=7d
use_temp_path=off;
# 默认代理设置
proxy_http_version 1.1;
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_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
proxy_connect_timeout 10s;
proxy_read_timeout 60s;
proxy_send_timeout 30s;
proxy_buffer_size 4k;
proxy_buffers 8 32k;
proxy_busy_buffers_size 64k;
# 引入站点配置
include /etc/nginx/conf.d/*.conf;
}
总结
本章介绍了 Nginx 性能优化的方方面面:
- 系统优化:文件描述符、内核参数、TCP 调优
- 进程优化:worker_processes、worker_connections、CPU 绑定
- 网络优化:sendfile、keepalive、缓冲区配置
- 压缩优化:Gzip、Brotli、预压缩
- 缓存优化:浏览器缓存、文件缓存、代理缓存
- 连接优化:upstream keepalive、超时配置
- 性能测试:ab、wrk、siege
- 瓶颈排查:CPU、内存、I/O、网络