Nginx2026-04-15·7 分钟
Nginx 性能调优
覆盖 Nginx 连接、缓存、压缩与负载能力优化的实用策略。
Nginx 性能调优
1. worker_processes 与 worker_connections
nginx
worker_processes auto;
worker_connections 1024;worker_processes auto;让 Nginx 依据 CPU 自动分配进程数。- 计算最大并发连接数:
worker_processes * worker_connections。
2. keepalive 与连接复用
nginx
keepalive_timeout 65;
keepalive_requests 100;- 保持连接可降低 TCP 握手成本。
- 对上游服务使用
keepalive,减少后端连接创建开销。
nginx
upstream backend {
server 127.0.0.1:8080;
keepalive 32;
}3. 静态文件缓存与压缩
nginx
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;nginx
location ~* \.(js|css|png|jpg|jpeg|gif|svg)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}- 开启
gzip可以减少发送带宽。 - 静态文件资源设置合理缓存头。
4. sendfile 与 aio
nginx
sendfile on;
tcp_nopush on;
tcp_nodelay on;sendfile on;提升静态文件传输性能。- 在高 IO 场景下可启用
aio。
5. 负载均衡与健康检查
least_conn对长连接服务更友好。- 配置
max_fails与fail_timeout过滤不可用后端。 - 健康检查能避免将请求发送给不可用节点。
6. 限流与防刷
nginx
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
limit_req zone=req_limit burst=20 nodelay;- 对频繁请求接口进行限流,防止突发请求过载。
limit_conn可限制并发连接数。
7. 日志级别与监控
- 生产环境可设置
access_log off;或按需采样,降低磁盘写入。 error_log设为warn及以上,避免日志过大。
8. 监测与分析
- 使用
nginx_status模块查看活动连接数。 - 结合
Grafana、Prometheus进行指标分析。
Nginx性能调优