Nginx 高并发性能优化:从入门到精通


阿里云特惠 - 新用户专享

Nginx 高并发性能优化:从入门到精通

Nginx 以其高性能、低资源占用成为 Web 服务器的首选。但默认配置远远不能发挥 Nginx 的真正实力。本文深入剖析 Nginx 性能优化的各个维度,让您的服务器性能提升 10 倍以上。

一、Worker 进程优化

# 基础配置
worker_processes auto;  # 自动设置为 CPU 核心数
worker_rlimit_nofile 65535;  # 提升文件描述符限制

events {
    worker_connections 10240;  # 每个 Worker 的最大连接数
    use epoll;  # Linux 下使用 epoll 事件模型
    multi_accept on;  # 同时接受多个连接
}

计算公式:最大并发数 = worker_processes × worker_connections

例如:8 核 CPU × 10240 = 81920 并发连接

二、内核参数优化

# 编辑 /etc/sysctl.conf
net.core.somaxconn = 65535  # 增加监听队列长度
net.ipv4.tcp_max_syn_backlog = 8192  # SYN 队列大小
net.ipv4.tcp_tw_reuse = 1  # 允许复用 TIME_WAIT 端口
net.ipv4.tcp_fin_timeout = 15  # 减少 TIME_WAIT 超时时间
net.ipv4.tcp_keepalive_time = 600  # TCP keepalive 时间
net.ipv4.tcp_max_tw_buckets = 6000  # TIME_WAIT 桶数量
net.ipv4.ip_local_port_range = 1024 65535  # 本地端口范围

# 应用配置
sysctl -p

三、HTTP 优化

http {
    # 开启高效传输
    sendfile on;  # 零拷贝文件传输
    tcp_nopush on;  # 与 sendfile 配合使用
    tcp_nodelay on;  # 禁用 Nagle 算法

    # Keep-Alive 优化
    keepalive_timeout 65;  # 长连接超时
    keepalive_requests 1000;  # 每个连接最多处理 1000 个请求

    # Gzip 压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;  # 大于 1KB 才压缩
    gzip_comp_level 6;  # 压缩级别 1-9,6 是平衡点
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml;

    # 缓存配置
    open_file_cache max=10000 inactive=30s;  # 缓存文件句柄
    open_file_cache_valid 60s;  # 缓存验证时间
    open_file_cache_min_uses 2;  # 最少使用 2 次才缓存
    open_file_cache_errors on;  # 缓存打开失败信息
}

四、静态资源优化

# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|ttf|eot|svg)$ {
    expires 30d;  # 浏览器缓存 30 天
    add_header Cache-Control "public, immutable";
    access_log off;  # 不记录访问日志
}

# 禁止访问隐藏文件
location ~ /\. {
    deny all;
    access_log off;
    log_not_found off;
}

# 防止盗链
location ~* \.(gif|jpg|png|css|js)$ {
    valid_referers none blocked *.example.com;
    if ($invalid_referer) {
        return 403;
    }
}

五、反向代理优化

upstream backend {
    least_conn;  # 最少连接负载均衡
    server 192.168.1.10:8080 weight=3 max_fails=3 fail_timeout=30s;
    server 192.168.1.11:8080 weight=1 max_fails=3 fail_timeout=30s;
    keepalive 32;  # 保持 32 个长连接到后端
    keepalive_timeout 60s;
    keepalive_requests 1000;
}

server {
    location /api/ {
        proxy_pass http://backend;
        proxy_http_version 1.1;  # 使用 HTTP/1.1
        proxy_set_header Connection "";  # 清空 Connection 头

        # 超时配置
        proxy_connect_timeout 10s;
        proxy_read_timeout 60s;
        proxy_send_timeout 60s;

        # 缓冲优化
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        proxy_busy_buffers_size 8k;

        # 头信息传递
        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_next_upstream error timeout http_500 http_502 http_503;
        proxy_next_upstream_tries 2;
    }
}

六、HTTPS 优化

server {
    listen 443 ssl http2;
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;

    # SSL 协议优化
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers off;

    # SSL 会话缓存
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;

    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/ssl/certs/chain.crt;

    # HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}

七、限流防护

http {
    # 请求速率限制
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

    # 并发连接限制
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
}

location /api/ {
    # 速率限制
    limit_req zone=api_limit burst=20 nodelay;

    # 连接限制
    limit_conn conn_limit 10;

    # 超出限制返回 429
    limit_req_status 429;
    limit_conn_status 429;
}

八、日志优化

http {
    # 自定义日志格式
    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;
    error_log /var/log/nginx/error.log warn;

    # 访问日志不记录某些请求
    location = /favicon.ico {
        access_log off;
        log_not_found off;
    }
}

九、性能测试

# 使用 wrk 进行压测
wrk -t4 -c100 -d30s http://localhost/

# 使用 ab(Apache Bench)进行压测
ab -n 10000 -c 100 http://localhost/

# 使用 siege 进行压测
siege -c 100 -t 30s http://localhost/

总结

Nginx 性能优化需要从多个维度入手:Worker 进程配置、内核参数调优、HTTP 协议优化、静态资源缓存、反向代理配置、HTTPS 加速、限流防护。每一点优化都能带来性能提升,综合应用可以让您的服务器应对数十万并发连接。

发表评论