Linux运维5 min read

Nginx 高性能配置与调优实战

Nginx 性能调优全景

Nginx 以其高并发、低内存占用的特性成为 Web 服务器和反向代理的首选。但默认配置远非最优,合理调优可以将性能提升数倍。

Worker 进程优化

# worker_processes 应设置为 CPU 核心数
worker_processes auto;

# 每个 worker 的最大连接数 = worker_connections × worker_processes
events {
    use epoll;                    # Linux 下最优事件模型
    worker_connections 65535;     # 受系统 open files 限制
    multi_accept on;              # 一次接受所有新连接
}

系统级配合

# 修改系统 open files 限制
echo "nginx soft nofile 655350" >> /etc/security/limits.conf
echo "nginx hard nofile 655350" >> /etc/security/limits.conf

# 调整内核网络参数
cat >> /etc/sysctl.conf << EOF
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        # TIME_WAIT 复用
net.ipv4.tcp_fin_timeout = 30    # 缩短 FIN 超时
EOF
sysctl -p

连接与缓冲优化

http {
    # 高效文件传输
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    # 长连接(减少握手开销)
    keepalive_timeout 65;
    keepalive_requests 1000;

    # 客户端缓冲(防止慢客户端占用 worker)
    client_body_buffer_size 128k;
    client_max_body_size 100m;
    client_header_buffer_size 4k;
    large_client_header_buffers 4 32k;

    # 代理缓冲(保护后端)
    proxy_buffering on;
    proxy_buffer_size 4k;
    proxy_buffers 8 64k;
    proxy_busy_buffers_size 128k;
}

Gzip 压缩策略

gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;          # 压缩等级 1-9,6 是性价比最优
gzip_min_length 1024;       # 小于此值不压缩
gzip_buffers 16 8k;

# 仅压缩可文本类型(图片/视频已压缩不必再压)
gzip_types
  text/plain
  text/css
  text/xml
  text/javascript
  application/javascript
  application/json
  application/xml
  application/rss+xml
  image/svg+xml;

静态资源缓存

# 版本化资源 — 永久缓存
location /assets/ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    add_header X-Content-Type-Options "nosniff";
}

# 图片资源 — 长缓存
location ~* \.(jpg|jpeg|png|gif|webp|svg|ico)$ {
    expires 30d;
    add_header Cache-Control "public";
    access_log off;
}

# HTML — 不缓存
location ~* \.html$ {
    expires -1;
    add_header Cache-Control "no-store, no-cache, must-revalidate";
}

反向代理与负载均衡

upstream backend {
    # 负载均衡算法
    # least_conn;      # 最少连接(长连接场景)
    # ip_hash;         # 会话保持
    # fair;            # 响应时间(需 nginx-upstream-fair 模块)

    # 默认:加权轮询
    server 10.0.1.10:8080 weight=3 max_fails=3 fail_timeout=30s;
    server 10.0.1.11:8080 weight=2 max_fails=3 fail_timeout=30s;
    server 10.0.1.12:8080 weight=1 backup;  # 备份节点

    # 长连接池(减少握手开销)
    keepalive 64;
    keepalive_timeout 60s;
    keepalive_requests 1000;
}

server {
    location /api/ {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";          # 支持 keepalive

        # 正确传递客户端信息
        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_connect_timeout 10s;
        proxy_send_timeout 30s;
        proxy_read_timeout 60s;
    }
}

FastCGI 缓存(PHP 场景)

# 定义缓存区
fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2
                   keys_zone=WORDPRESS:200m
                   max_size=2g inactive=60m
                   use_temp_path=off;

server {
    set $skip_cache 0;

    # 管理后台不缓存
    if ($request_uri ~* "/wp-admin/|/wp-login.php") {
        set $skip_cache 1;
    }

    location ~ \.php$ {
        fastcgi_pass php-fpm;
        fastcgi_cache WORDPRESS;
        fastcgi_cache_key "$scheme$request_method$host$request_uri";
        fastcgi_cache_valid 200 60m;
        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;
    }
}

限流策略

# 定义限流区域(基于IP,每秒10请求)
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

# 连接数限制
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

server {
    location /api/ {
        # 请求限流(burst 允许瞬间20突发,nodelay 不延迟处理)
        limit_req zone=api_limit burst=20 nodelay;
        limit_conn conn_limit 10;

        proxy_pass http://backend;
    }
}

性能压测验证

# 使用 wrk 进行基准测试
wrk -t12 -c400 -d30s http://your-server/

# 使用 ab 快速测试
ab -n 10000 -c 200 http://your-server/

# 使用 vegeta 持续压测
echo "GET http://your-server/" | vegeta attack -duration=30s -rate=1000 | vegeta report

调优金句:先测量,再优化。盲目修改配置往往适得其反。每次改动后用压测工具验证效果,记录基准数据,形成可量化的优化路径。

分享:

相关文章