linux中级_Nginx性能优化

TJCcc 发布于 2026-01-30 20 次阅读


一、性能优化的基本思路与流程

1.1 优化前的准备与分析

# 1. 系统瓶颈分析
top                   # 查看CPU负载、内存使用
vmstat 1 10          # 查看系统整体性能
iostat -x 1          # 查看磁盘I/O
netstat -an | grep :80 | wc -l  # 查看80端口连接数
ss -s                # 查看socket统计

# 2. Nginx状态监控(需安装stub_status模块)
location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}
# 访问结果:
# Active connections: 291
# server accepts handled requests: 16630948 16630948 31070465
# Reading: 6 Writing: 179 Waiting: 106

1.2 性能指标与优化目标

指标优化目标监控方法
QPS静态资源:>10000/s
动态代理:>5000/s
ab、wrk测试
响应时间<50ms(静态)
<200ms(动态)
日志分析
并发连接数根据内存调整nginx_status
错误率<0.1%错误日志监控

二、系统层优化(深度详解)

2.1 文件句柄数优化(重点)

# 查看当前限制
ulimit -n           # 用户级限制
cat /proc/sys/fs/file-nr  # 系统已使用/最大限制

# 永久配置(/etc/security/limits.conf)
# * 代表所有用户,也可以指定用户名
* soft nofile 65535   # 软限制(警告阈值)
* hard nofile 65535   # 硬限制(不可超越)
* soft nproc 65535
* hard nproc 65535

# 系统级全局限制(/etc/sysctl.conf)
fs.file-max = 1000000      # 系统最大文件句柄数
fs.nr_open = 1000000       # 单个进程最大文件句柄数

# 针对Nginx进程(nginx.conf)
worker_rlimit_nofile 65535;  # 每个worker进程可打开的文件数

2.2 网络协议栈优化

# /etc/sysctl.conf 配置详解
net.ipv4.tcp_tw_reuse = 1          # 启用TIME-WAIT重用
net.ipv4.tcp_tw_recycle = 1        # 快速回收TIME-WAIT(注意NAT问题)
net.ipv4.tcp_fin_timeout = 30      # FIN-WAIT-2超时时间
net.ipv4.tcp_keepalive_time = 1200 # TCP长连接保活时间
net.ipv4.tcp_max_tw_buckets = 5000 # 最大TIME-WAIT数量
net.ipv4.tcp_max_syn_backlog = 8192 # SYN队列长度
net.ipv4.tcp_syncookies = 1        # 防止SYN洪水攻击
net.core.somaxconn = 65535         # 连接队列最大值
net.core.netdev_max_backlog = 65535 # 网卡收包队列
net.ipv4.tcp_rmem = 4096 87380 6291456  # TCP读缓冲区
net.ipv4.tcp_wmem = 4096 16384 4194304  # TCP写缓冲区
net.core.rmem_max = 6291456
net.core.wmem_max = 4194304

# 生效命令
sysctl -p

2.3 TIME-WAIT问题深度分析

# 问题现象:大量端口处于TIME-WAIT状态
netstat -n | awk '/^tcp/ {++state[$NF]} END {for(key in state) print key,"\t",state[key]}'

# 优化方案:
# 1. 开启端口复用
net.ipv4.tcp_tw_reuse = 1
# 2. 调整本地端口范围
net.ipv4.ip_local_port_range = 1024 65535
# 3. Nginx配置长连接减少短连接
keepalive_timeout 65;
keepalive_requests 100;

三、Nginx核心配置优化

3.1 进程与连接模型

# ============ main配置段 ============
# CPU核心数查询:cat /proc/cpuinfo | grep processor | wc -l
worker_processes auto;                 # 自动设置为CPU核心数

# CPU亲和性绑定(三种方式)
# 方式1:自动绑定(推荐)
worker_cpu_affinity auto;

# 方式2:手动绑定(8核心示例)
worker_processes 8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 
                    00010000 00100000 01000000 10000000;

# 方式3:分组绑定(4核心,每个worker绑定2个CPU)
worker_processes 4;
worker_cpu_affinity 0101 1010 0101 1010;

# ============ events配置段 ============
events {
    # 选择高效的事件模型
    # epoll(Linux 2.6+) / kqueue(FreeBSD) / select(通用但性能差)
    use epoll;

    # 每个worker最大连接数 = worker_connections × worker_processes
    # 注意:不能超过系统最大文件句柄数
    worker_connections 10240;

    # 开启多连接接受模式(Linux 2.6+)
    multi_accept on;

    # 惊群问题优化(Linux 3.9+)
    accept_mutex off;         # 关闭accept锁,使用内核负载均衡
    # 或使用reuseport(Linux 3.9+,Nginx 1.9.1+)
    reuse_port on;
}

# ============ 连接限制与调优 ============
http {
    # 单个连接最大请求数
    keepalive_requests 1000;

    # 长连接超时时间
    keepalive_timeout 65s;

    # 发送超时时间
    send_timeout 60s;

    # 客户端请求体最大大小
    client_max_body_size 100m;

    # 客户端请求头缓冲区大小
    client_header_buffer_size 32k;
    large_client_header_buffers 4 64k;
}

3.2 代理服务深度优化

upstream backend_servers {
    # 后端服务器配置
    server 192.168.1.101:8080 weight=5 max_fails=3 fail_timeout=30s;
    server 192.168.1.102:8080 weight=5 max_fails=3 fail_timeout=30s;
    server 192.168.1.103:8080 weight=5 max_fails=3 fail_timeout=30s;

    # 长连接池配置
    keepalive 32;                 # 连接池大小
    keepalive_timeout 60s;        # 连接空闲超时
    keepalive_requests 1000;      # 每个连接最大请求数

    # 负载均衡算法(默认轮询)
    # least_conn;                 # 最少连接
    # ip_hash;                    # IP哈希
    # hash $request_uri;          # URL哈希
    # fair;                       # 第三方模块,按响应时间
}

server {
    location /api/ {
        proxy_pass http://backend_servers;

        # HTTP协议版本
        proxy_http_version 1.1;
        proxy_set_header Connection "";

        # 超时配置
        proxy_connect_timeout 5s;     # 连接后端超时
        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_temp_file_write_size 16k; # 临时文件写入大小

        # 关闭代理缓存(调试用)
        # proxy_buffering off;

        # 头信息传递
        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 invalid_header http_500 http_502 http_503 http_504;
        proxy_next_upstream_tries 3;     # 重试次数
        proxy_next_upstream_timeout 10s; # 重试超时

        # 缓存配置
        proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m 
                         max_size=1g inactive=60m use_temp_path=off;
        proxy_cache api_cache;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        proxy_cache_bypass $http_cache_control;
        add_header X-Cache-Status $upstream_cache_status;
    }
}

四、静态资源优化(极致性能)

4.1 缓存策略分层优化

server {
    listen 80;
    server_name static.example.com;
    root /data/static;

    # 图片文件:长期缓存(内容哈希命名)
    location ~* \.(jpg|jpeg|png|gif|ico|webp|svg)$ {
        expires 365d;                    # 缓存一年
        add_header Cache-Control "public, immutable";
        add_header Pragma "public";

        # 禁用日志减少I/O
        access_log off;
        log_not_found off;

        # 开启sendfile高效传输
        sendfile on;
        tcp_nopush on;

        # 对已压缩图片不重复压缩
        gzip off;
    }

    # CSS/JS文件:中期缓存(带版本号)
    location ~* \.(css|js)$ {
        expires 30d;
        add_header Cache-Control "public, must-revalidate";

        # 开启Gzip压缩
        gzip on;
        gzip_types text/css application/javascript;
        gzip_min_length 1024;
        gzip_comp_level 6;

        # Brotli压缩(Nginx 1.11.5+)
        # brotli on;
        # brotli_types text/css application/javascript;
        # brotli_comp_level 6;
    }

    # 字体文件:长期缓存
    location ~* \.(woff|woff2|ttf|eot|otf)$ {
        expires 365d;
        add_header Cache-Control "public, immutable";
        add_header Access-Control-Allow-Origin "*";
    }

    # 视频文件:大文件分片传输
    location ~* \.(mp4|webm|avi|flv)$ {
        expires 7d;

        # 启用MP4流媒体模块
        mp4;
        mp4_buffer_size 1m;
        mp4_max_buffer_size 5m;

        # 限制下载速度(防止带宽耗尽)
        limit_rate_after 10m;  # 10MB后限速
        limit_rate 500k;       # 限速500KB/s
    }

    # 开发环境:禁用缓存
    location ~* \.(html|htm)$ {
        if ($arg_debug) {
            add_header Cache-Control "no-cache, no-store, must-revalidate";
            add_header Pragma "no-cache";
            expires 0;
        }
    }
}

4.2 文件传输优化

http {
    # 高效文件传输
    sendfile on;               # 零拷贝技术,绕过用户空间
    sendfile_max_chunk 512k;   # 每次发送的最大数据块

    # TCP优化
    tcp_nopush on;             # 当数据包满时再发送(静态资源)
    tcp_nodelay on;            # 立即发送数据包(API接口)

    # 文件打开缓存
    open_file_cache max=10000 inactive=30s;  # 缓存文件描述符
    open_file_cache_valid 60s;                # 缓存验证时间
    open_file_cache_min_uses 2;               # 最少使用次数
    open_file_cache_errors on;                # 缓存错误信息

    # 直接I/O(大文件传输)
    # aio on;                   # 异步I/O(Linux 2.6+)
    # directio 4m;             # 4MB以上文件使用直接I/O
    # output_buffers 2 1m;     # 输出缓冲区
}

4.3 Gzip压缩深度优化

http {
    gzip on;
    gzip_vary on;
    gzip_proxied any;          # 为所有代理请求启用压缩

    # 压缩级别权衡(1-9,数字越大CPU消耗越高)
    gzip_comp_level 6;

    # 最小压缩长度(小文件压缩得不偿失)
    gzip_min_length 1024;

    # 压缩缓冲区
    gzip_buffers 16 8k;

    # HTTP版本
    gzip_http_version 1.1;

    # 禁用旧版本IE
    gzip_disable "MSIE [1-6]\.";

    # 压缩类型(按优先级排序)
    gzip_types
        # 文本类型(压缩率高)
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/xml+rss

        # 字体类型
        font/ttf
        font/otf
        font/woff
        font/woff2
        application/vnd.ms-fontobject

        # 其他
        image/svg+xml;

    # Brotli压缩(更高效,需要安装模块)
    # brotli on;
    # brotli_static on;        # 预压缩文件支持
    # brotli_comp_level 6;
    # brotli_buffers 16 8k;
    # brotli_min_length 1024;
    # brotli_types text/plain text/css text/xml application/json application/javascript application/xml+rss image/svg+xml;
}

五、安全与访问控制优化

5.1 防盗链高级配置

# 基础防盗链
location ~* \.(jpg|png|gif|jpeg|bmp)$ {
    valid_referers none blocked 
                   server_names 
                   *.example.com 
                   ~\.google\. 
                   ~\.baidu\.;

    # 处理非法引用
    if ($invalid_referer) {
        # 方式1:返回403错误
        # return 403;

        # 方式2:重定向到警告图片
        rewrite ^(.*)$ /static/warning.jpg break;

        # 方式3:返回空图片
        # empty_gif;

        # 方式4:记录日志并返回404
        # access_log /var/log/nginx/steal.log;
        # return 404;
    }

    # 添加水印(需要image_filter模块)
    # image_filter resize 800 600;
    # image_filter watermark /path/to/watermark.png;
}

# 防盗链白名单
map $http_referer $allow_steal {
    default                  0;
    "~*example\.com"        1;
    "~*google\.com"         1;
    ""                      1;  # 直接访问允许
}

location ~* \.(mp4|flv)$ {
    if ($allow_steal = 0) {
        return 403;
    }
}

5.2 限流与防攻击

# 连接数限制
limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;

# 请求频率限制
limit_req_zone $binary_remote_addr zone=req_perip:10m rate=10r/s;
limit_req_zone $server_name zone=req_perserver:10m rate=100r/s;

server {
    # 限制单个IP并发连接数
    limit_conn perip 10;
    limit_conn perserver 100;

    # 限制请求频率(突发限制)
    limit_req zone=req_perip burst=20 nodelay;
    limit_req zone=req_perserver burst=100;

    # 下载限速
    location /download/ {
        # 前10MB不限速
        limit_rate_after 10m;
        # 之后限速500KB/s
        limit_rate 500k;

        # 限制下载线程数(需nginx-upload-module)
        # upload_limit_rate 512k;
        # upload_max_file_size 100m;
    }

    # API接口特殊限制
    location /api/ {
        # 更严格的限制
        limit_req zone=req_perip burst=5 nodelay;
        limit_conn perip 5;

        # 慢请求日志记录
        log_format slowlog '$remote_addr - $remote_user [$time_local] '
                          '"$request" $status $body_bytes_sent '
                          '"$http_referer" "$http_user_agent" '
                          '$request_time $upstream_response_time';
        access_log /var/log/nginx/slow.log slowlog if=$slow;

        # 定义慢请求(超过2秒)
        set $slow 0;
        if ($request_time > 2) {
            set $slow 1;
        }
    }
}

5.3 DDoS防护配置

# 基础防护
http {
    # 关闭服务器标记
    server_tokens off;

    # 限制请求方法
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }

    # User-Agent过滤
    if ($http_user_agent ~* (wget|curl|scan|bot|spider)) {
        return 403;
    }

    # 阻止非法请求
    location ~* \.(php|asp|aspx|jsp|pl|sh|exe)$ {
        deny all;
    }
}

# 高级防护:请求频率分析
geo $limit {
    default 0;
    10.0.0.0/8 0;      # 内网不限速
    192.168.0.0/16 0;
}

map $limit $limit_key {
    0 "";
    1 $binary_remote_addr;
}

limit_req_zone $limit_key zone=req_zone:10m rate=5r/s;

server {
    location / {
        limit_req zone=req_zone burst=10 nodelay;
    }
}

六、跨域与缓存控制

6.1 跨域访问(CORS)完整配置

# 预检请求处理
location / {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, PATCH';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
        add_header 'Access-Control-Max-Age' 86400;  # 缓存24小时
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
    }

    # 实际请求处理
    if ($request_method ~ ^(GET|POST|PUT|DELETE|PATCH)$) {
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, PATCH' always;
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;

        # 携带Cookie时需要具体域名
        # add_header 'Access-Control-Allow-Origin' 'https://www.example.com' always;
        # add_header 'Access-Control-Allow-Credentials' 'true' always;
    }
}

# 静态资源跨域
location ~* \.(woff|woff2|ttf|eot|otf)$ {
    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET";
    expires 365d;
}

# JSONP支持
location /api/jsonp {
    if ($arg_callback) {
        add_header Content-Type 'application/javascript; charset=utf-8';
        return 200 '$arg_callback({"status":"ok"})';
    }
    return 400 'Missing callback parameter';
}

6.2 缓存控制策略

# 根据文件类型设置缓存策略
map $uri $cache_control {
    # 静态资源长期缓存
    ~*\.(jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ "public, max-age=31536000, immutable";

    # CSS/JS中期缓存
    ~*\.(css|js)$ "public, max-age=604800, must-revalidate";

    # HTML不缓存或短期缓存
    ~*\.(html|htm)$ "no-cache, max-age=0, must-revalidate";

    # API响应不缓存
    ~*^/api/ "no-store, no-cache, must-revalidate, max-age=0";

    # 默认设置
    default "public, max-age=3600";
}

server {
    location / {
        # 设置Cache-Control头
        add_header Cache-Control $cache_control;

        # 设置Expires头(兼容HTTP/1.0)
        expires 1h;

        # ETag生成(默认开启,大文件可关闭)
        etag on;

        # Last-Modified头
        if_modified_since exact;

        # 添加Vary头(用于区分压缩版本)
        add_header Vary "Accept-Encoding";
    }

    # 动态内容:完全禁用缓存
    location ~ ^/(api|admin|login)/ {
        add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";
        add_header Pragma "no-cache";
        expires 0;

        # 禁用代理缓存
        proxy_no_cache 1;
        proxy_cache_bypass 1;
    }
}

七、监控与日志优化

7.1 结构化日志配置

# JSON格式日志(便于ELK分析)
log_format json_combined escape=json
    '{'
    '"time_local":"$time_local",'
    '"remote_addr":"$remote_addr",'
    '"remote_user":"$remote_user",'
    '"request":"$request",'
    '"status":"$status",'
    '"body_bytes_sent":"$body_bytes_sent",'
    '"request_time":"$request_time",'
    '"http_referer":"$http_referer",'
    '"http_user_agent":"$http_user_agent",'
    '"http_x_forwarded_for":"$http_x_forwarded_for",'
    '"upstream_addr":"$upstream_addr",'
    '"upstream_response_time":"$upstream_response_time",'
    '"upstream_status":"$upstream_status",'
    '"request_length":"$request_length",'
    '"server_name":"$server_name",'
    '"server_port":"$server_port",'
    '"scheme":"$scheme",'
    '"request_method":"$request_method",'
    '"uri":"$uri",'
    '"args":"$args",'
    '"connection":"$connection",'
    '"connection_requests":"$connection_requests",'
    '"pipe":"$pipe"'
    '}';

# 性能监控日志
log_format perf_log
    '$remote_addr - $remote_user [$time_local] '
    '"$request" $status $body_bytes_sent '
    '"$http_referer" "$http_user_agent" '
    'rt=$request_time uct="$upstream_connect_time" '
    'uht="$upstream_header_time" urt="$upstream_response_time"';

# 错误日志分级
error_log /var/log/nginx/error.log warn;
# 日志级别:debug | info | notice | warn | error | crit | alert | emerg

# 访问日志配置
access_log /var/log/nginx/access.log json_combined buffer=32k flush=5s;
# buffer:日志缓冲区大小
# flush:缓冲区刷新时间

# 静态资源日志关闭
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2)$ {
    access_log off;
    log_not_found off;
}

7.2 实时监控配置

# 状态页面(需要nginx-module-vts)
location /status {
    vhost_traffic_status_display;
    vhost_traffic_status_display_format html;
    access_log off;
    allow 127.0.0.1;
    allow 10.0.0.0/8;
    deny all;
}

# Prometheus监控(需要nginx-module-vts)
location /metrics {
    vhost_traffic_status_display;
    vhost_traffic_status_display_format prometheus;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

# 健康检查端点
location /health {
    access_log off;
    return 200 "healthy\n";
    add_header Content-Type text/plain;
}

# 性能统计
location /stub_status {
    stub_status;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

八、高级优化技巧

8.1 多级缓存架构

# 内存缓存(热点数据)
proxy_cache_path /dev/shm/nginx_cache levels=1:2 keys_zone=hot_cache:10m
                 max_size=100m inactive=1h use_temp_path=off;

# 磁盘缓存(全量数据)
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=cache_zone:100m
                 max_size=10g inactive=30d use_temp_path=off;

server {
    location / {
        # 先查内存缓存
        proxy_cache hot_cache;
        proxy_cache_valid 200 302 10m;

        # 缓存键设计
        proxy_cache_key "$scheme$request_method$host$request_uri$cookie_user";

        # 缓存锁定(防止惊群)
        proxy_cache_lock on;
        proxy_cache_lock_timeout 5s;

        # 陈旧数据响应
        proxy_cache_use_stale error timeout invalid_header updating
                               http_500 http_502 http_503 http_504;

        # 缓存绕过条件
        proxy_cache_bypass $http_cache_control;

        # 添加缓存命中头
        add_header X-Cache-Status $upstream_cache_status;
        add_header X-Cache-Hit $upstream_cache_status;
    }
}

8.2 HTTP/2优化

server {
    listen 443 ssl http2;  # 启用HTTP/2
    http2_push_preload on;  # 服务器推送

    # HTTP/2优化参数
    http2_max_concurrent_streams 128;  # 最大并发流
    http2_max_field_size 16k;          # 头部字段最大大小
    http2_max_header_size 64k;         # 头部最大大小

    # 针对HTTP/2的优化
    location / {
        # 资源预加载提示
        add_header Link "</style.css>; rel=preload; as=style";
        add_header Link "</script.js>; rel=preload; as=script";
    }
}

8.3 动态模块加载

# 编译时选择高性能模块
./configure \
    --with-threads \                   # 线程池支持
    --with-file-aio \                  # 异步文件I/O
    --with-http_realip_module \        # 真实IP模块
    --with-http_addition_module \      # 响应添加模块
    --with-http_xslt_module \          # XSLT转换
    --with-http_image_filter_module \  # 图片处理
    --with-http_geoip_module \         # GeoIP支持
    --with-http_sub_module \           # 字符串替换
    --with-http_dav_module \           # WebDAV支持
    --with-http_flv_module \           # FLV视频支持
    --with-http_mp4_module \           # MP4视频支持
    --with-http_gunzip_module \        # Gzip解压
    --with-http_gzip_static_module \   # 静态Gzip
    --with-http_auth_request_module \  # 认证请求
    --with-http_random_index_module \  # 随机目录索引
    --with-http_secure_link_module \   # 安全链接
    --with-http_slice_module \         # 大文件分片
    --with-http_stub_status_module \   # 状态监控
    --with-mail \                      # 邮件代理
    --with-mail_ssl_module \           # 邮件SSL
    --with-stream \                    # TCP/UDP代理
    --with-stream_ssl_module \         # 流SSL
    --with-stream_realip_module \      # 流真实IP
    --with-stream_geoip_module \       # 流GeoIP
    --with-stream_ssl_preread_module \ # SSL预读
    --with-compat \                    # 兼容模式
    --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' \
    --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

九、性能测试与验证

9.1 压力测试脚本

#!/bin/bash
# nginx-stress-test.sh

# 测试参数
CONCURRENCY=(100 500 1000 2000 5000)
DURATION=60
URL="http://localhost/"

echo "========== Nginx性能压力测试 =========="
echo "测试URL: $URL"
echo "单次测试时长: ${DURATION}秒"
echo ""

for C in "${CONCURRENCY[@]}"; do
    echo "▶ 测试并发数: $C"
    echo "----------------------------------------"

    # 使用wrk进行测试(更准确)
    wrk -t$(nproc) -c$C -d${DURATION}s --latency $URL

    # 或者使用ab
    # ab -k -c $C -t $DURATION $URL | grep -E "Requests per second:|Time per request:|Failed requests:"

    echo ""
    sleep 10  # 等待系统恢复
done

# 系统资源监控
echo "========== 系统资源监控 =========="
top -bn1 | grep -E "Cpu|Mem|Load"
echo ""
free -h
echo ""
netstat -s | grep -E "listen|retrans"

9.2 性能基准检查表

## Nginx性能优化检查清单

### ✅ 系统层
- [ ] 文件句柄数 > 65535
- [ ] TIME-WAIT优化已配置
- [ ] 网络缓冲区已调整
- [ ] 系统时钟同步

### ✅ Nginx配置
- [ ] worker_processes = CPU核心数
- [ ] worker_connections 合理设置
- [ ] keepalive_timeout 已优化
- [ ] sendfile/tcp_nopush/tcp_nodelay 已启用

### ✅ 静态资源
- [ ] 缓存策略分层配置
- [ ] Gzip压缩已优化
- [ ] 图片格式优化(WebP)
- [ ] 防盗链已配置

### ✅ 代理服务
- [ ] 长连接池已配置
- [ ] 缓冲区大小合理
- [ ] 超时时间适当
- [ ] 负载均衡策略合理

### ✅ 安全防护
- [ ] 请求限流已配置
- [ ] DDoS防护基础措施
- [ ] 敏感信息已过滤
- [ ] 错误信息已隐藏

### ✅ 监控告警
- [ ] 访问日志结构化
- [ ] 错误日志分级
- [ ] 性能监控已部署
- [ ] 告警阈值已设置

十、🔧 故障排查与调试

10.1 常见问题排查命令

# 1. 查看Nginx状态
systemctl status nginx
nginx -t                      # 测试配置文件
nginx -s reload              # 重载配置

# 2. 连接状态分析
ss -tan | grep :80 | awk '{print $1}' | sort | uniq -c
netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'

# 3. 实时监控
tail -f /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c
ngxtop                       # 实时监控工具

# 4. 性能分析
strace -p $(pidof nginx) -c  # 系统调用跟踪
perf top -p $(pidof nginx)   # 性能分析

# 5. 内存泄漏检测
valgrind --tool=memcheck --leak-check=full nginx

# 6. 配置文件调试
nginx -T                      # 打印完整配置

10.2 调试配置模板

# debug.conf - 调试专用配置
server {
    listen 80;
    server_name debug.example.com;

    # 开启详细日志
    access_log /var/log/nginx/debug_access.log json_combined;
    error_log /var/log/nginx/debug_error.log debug;

    # 关闭缓存便于调试
    proxy_buffering off;
    fastcgi_buffering off;
    uwsgi_buffering off;

    # 添加调试头信息
    add_header X-Debug-Request-ID $request_id;
    add_header X-Debug-Upstream $upstream_addr;
    add_header X-Debug-Cache $upstream_cache_status;

    location / {
        # 记录请求时间
        set $start_time $msec;

        # 代理到后端
        proxy_pass http://backend;

        # 记录响应时间
        set $end_time $msec;
        set $response_time $end_time-$start_time;

        # 输出调试信息
        add_header X-Debug-Response-Time $response_time;
        add_header X-Debug-Request-Time $request_time;
        add_header X-Debug-Upstream-Time $upstream_response_time;
    }

    # 模拟慢响应(测试用)
    location /slow {
        echo_sleep 5;  # 等待5秒
        echo "Slow response";
    }

    # 错误模拟
    location /error {
        return 500 "Internal Server Error";
    }
}

总结与建议

优化优先级建议:

  1. 第一优先级(必需)
  • 文件句柄数优化
  • worker_processes和worker_connections
  • Gzip压缩
  • 静态资源缓存
  1. 第二优先级(推荐)
  • TCP内核参数优化
  • 代理长连接配置
  • 防盗链和安全限制
  • 日志结构化
  1. 第三优先级(高级)
  • HTTP/2优化
  • 多级缓存架构
  • 高级负载均衡策略
  • 实时监控系统

性能测试建议:

  • 每次优化后都要进行压力测试
  • 生产环境优化前先在测试环境验证
  • 监控优化前后的性能对比
  • 定期进行性能回归测试

版本建议:

  • 使用Nginx官方稳定版本
  • 定期更新安全补丁
  • 考虑使用OpenResty(Nginx + Lua)进行更灵活的优化

唯有极致沉淀,才能造就辉煌。
最后更新于 2026-01-30