Nginxperformanceoptimizationtutorial

LearningNginxperformanceoptimization coreparameter, configurationtechniques and best practices, improvingserver response速度 and concurrentprocessingcapacity

performanceoptimizationoverview

for what需要performanceoptimization?

in high concurrent场景 under , Nginxserver performance直接影响 to user体验 and system stable 性. through合理 performanceoptimization, 可以improvingNginx response速度, concurrentprocessingcapacity and resource利用率, from 而更 good 地满足userrequirements.

performanceoptimization 目标

performanceoptimization 范围

工作processconfiguration

工作process 作用

Nginxadopts many processmodel, 主process负责management工作process, 工作process负责processingpractical request. 合理configuration工作process数量 and 相关parameter, 可以充分利用systemresource, improvingconcurrentprocessingcapacity.

1. 工作process数量configuration

# configuration工作process数量
worker_processes auto;

# 绑定工作process to specificCPUcore
worker_cpu_affinity auto;

# 工作processpriority
worker_priority 0;

2. 工作processconnectionsconfiguration

# 每个工作process 最 big connections
worker_connections 10240;

# eventmodelconfiguration
events {
    # usingepolleventmodel (Linuxsystem推荐) 
    use epoll;
    
    # 每个工作process 最 big connections
    worker_connections 10240;
    
    # 允许同时接受 many 个连接
    multi_accept on;
}

# 工作process 最 big 打开file数
worker_rlimit_nofile 65536;

3. 工作processconfigurationparameter说明

4. 工作processconfiguration建议

连接 and 超时configuration

连接configuration important 性

合理configuration连接 and 超时parameter, 可以 has 效management连接resource, reducingresource浪费, improvingsystem response速度 and stable 性.

1. 连接configuration

# 连接configuration
http {
    # 开启 long 连接
    keepalive_timeout 65;
    
    # 每个 long 连接最 many processing request数
    keepalive_requests 100;
    
    #  long 连接 最 small 发送间隔
    keepalive_time 1h;
    
    #  long 连接 最 big 空闲时间
    keepalive_timeout 65;
    
    # 限制request体 big  small 
    client_max_body_size 10m;
    
    # 客户端头部超时时间
    client_header_timeout 10s;
    
    # 客户端request体超时时间
    client_body_timeout 10s;
    
    # 发送response超时时间
    send_timeout 10s;
    
    # server名称哈希表 big  small 
    server_names_hash_max_size 512;
    server_names_hash_bucket_size 64;
    
    # otherconfiguration
    ...
}

2. 超时configurationparameter说明

3. 连接configuration建议

cacheconfiguration

cache 作用

cache可以显著improvingNginx performance, reducing after 端server load, improvingresponse速度. Nginxsupport many 种cachemechanism, including浏览器cache, proxycache and FastCGIcacheetc..

1. 浏览器cacheconfiguration

# 浏览器cacheconfiguration
server {
    listen 80;
    server_name example.com;
    
    root /var/www/example.com;
    index index.html;
    
    #  for 静态file设置cache头
    location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|pdf|json)$ {
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
        add_header Last-Modified $date_gmt;
        if_modified_since off;
        etag off;
    }
    
    location / {
        try_files $uri $uri/ =404;
    }
}

2. proxycacheconfiguration

# proxycacheconfiguration
http {
    # 定义cachepath
    proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2 keys_zone=proxy_cache:10m max_size=10g inactive=60m use_temp_path=off;
    
    server {
        listen 80;
        server_name example.com;
        
        # 启用proxycache
        location / {
            proxy_pass http://backend;
            proxy_cache proxy_cache;
            proxy_cache_valid 200 30d;
            proxy_cache_valid 404 1m;
            proxy_cache_key "$scheme$request_method$host$request_uri";
            proxy_cache_bypass $http_pragma;
            proxy_cache_bypass $http_cache_control;
            add_header X-Cache-Status $upstream_cache_status;
            
            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;
        }
    }
    
    upstream backend {
        server localhost:8080;
        server localhost:8081;
    }
}

3. FastCGIcacheconfiguration (用于PHPetc.动态 in 容)

# FastCGIcacheconfiguration
http {
    # 定义cachepath
    fastcgi_cache_path /var/cache/nginx/fastcgi_cache levels=1:2 keys_zone=fastcgi_cache:10m max_size=10g inactive=60m use_temp_path=off;
    
    server {
        listen 80;
        server_name example.com;
        
        root /var/www/example.com;
        index index.php;
        
        # 启用FastCGIcache
        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
            
            # cacheconfiguration
            fastcgi_cache fastcgi_cache;
            fastcgi_cache_valid 200 30m;
            fastcgi_cache_valid 404 1m;
            fastcgi_cache_key "$scheme$request_method$host$request_uri";
            fastcgi_cache_bypass $http_pragma;
            fastcgi_cache_bypass $http_cache_control;
            add_header X-Cache-Status $upstream_cache_status;
        }
    }
}

4. cacheconfiguration建议

压缩configuration

压缩 作用

through压缩 in 容, 可以reducingnetwork传输量, improving传输速度, 降 low bandwidth消耗. NginxsupportGzip and Brotlietc.压缩algorithms, 可以根据客户端 supportcircumstances选择合适 压缩algorithms.

1. Gzip压缩configuration

# Gzip压缩configuration
http {
    # 启用Gzip压缩
    gzip on;
    
    # 添加 on  under 文头, 告诉cacheserver根据编码返回不同 response
    gzip_vary on;
    
    # 设置最 small 压缩file big  small 
    gzip_min_length 1024;
    
    # 设置压缩级别 (1-9) , 级别越 high 压缩效果越 good , 但CPU消耗也越 big 
    gzip_comp_level 6;
    
    # 设置压缩缓冲区 big  small 
    gzip_buffers 16 8k;
    
    # 设置support HTTPversion
    gzip_http_version 1.1;
    
    # 设置需要压缩 fileclass型
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
    
    # otherconfiguration
    ...
}

2. Brotli压缩configuration (需要Nginx 1.11.5+)

# Brotli压缩configuration
http {
    # 启用Brotli压缩
    brotli on;
    
    # 设置压缩级别 (1-11) 
    brotli_comp_level 6;
    
    # 设置最 small 压缩file big  small 
    brotli_min_length 1024;
    
    # 设置压缩缓冲区 big  small 
    brotli_buffers 16 8k;
    
    # 设置需要压缩 fileclass型
    brotli_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
    
    # Gzip压缩configuration (serving as after 备) 
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    
    # otherconfiguration
    ...
}

3. 压缩configuration建议

networkoptimization

networkoptimization important 性

networkparameter configuration直接影响 to Nginx networkperformance. throughoptimizationnetworkparameter, 可以reducingnetworklatency, improvingdata传输速度, 增强system stable 性.

1. TCPparameteroptimization

# TCPparameteroptimization
http {
    # 启用TCP_NODELAY, reducingnetworklatency
    tcp_nodelay on;
    
    # 启用TCP_CORK, improvingnetworkthroughput
    tcp_nopush on;
    
    # 设置套接字缓冲区 big  small 
    client_body_buffer_size 16k;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 8k;
    
    # otherconfiguration
    ...
}

#  in system级别optimizationTCPparameter
# /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 15
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.tcp_fastopen = 3
net.core.netdev_max_backlog = 65535

2. HTTP/2configuration

# HTTP/2configuration
server {
    listen 443 ssl http2;
    server_name example.com;
    
    # SSLconfiguration
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    
    # otherconfiguration
    root /var/www/example.com;
    index index.html;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

3. networkoptimization建议

filesystemoptimization

1. filesystemparameteroptimization

# filesystemoptimization
http {
    # 启用sendfile, reducingdata拷贝
    sendfile on;
    
    # 启用tcp_nopush,  and sendfile配合using, improvingperformance
    tcp_nopush on;
    
    # 启用directio,  for 于 big file传输, 绕过 in 核缓冲区
    directio 4m;
    
    # otherconfiguration
    ...
}

#  in system级别optimizationfilesystemparameter
# /etc/sysctl.conf
vm.swappiness = 10
vm.dirty_background_ratio = 5
vm.dirty_ratio = 10
vm.dirty_expire_centisecs = 3000
vm.dirty_writeback_centisecs = 500

# optimizationdiskschedulingalgorithms ( for 于SSD) 
# /etc/udev/rules.d/60-scheduler.rules
ACTION=="add|change", KERNEL=="sd*[!0-9]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="none"

2. filesystemoptimization建议

monitor and 调优

1. Nginxstatusmonitor

# configurationNginxstatusmonitor
http {
    # otherconfiguration
    ...
    
    server {
        listen 80;
        server_name example.com;
        
        # otherconfiguration
        ...
        
        # configurationstatusmonitor
        location /nginx_status {
            stub_status on;
            access_log off;
            allow 127.0.0.1;
            allow 192.168.1.0/24;
            deny all;
        }
    }
}

2. 常用monitortool

3. performance调优步骤

  1. 基准test: 建立performance基准, Understand当 before system performance水平
  2. monitor: deploymentmonitortool, 收集performancedata
  3. analysis: analysisperformancedata, 找出瓶颈
  4. optimization: 针 for 瓶颈foroptimization
  5. test: testoptimization效果, verification is 否达 to 预期目标
  6. 持续optimization: 定期monitor and analysis, 持续optimizationperformance

实践case: configuration high performanceNginxserver

fake设我们需要configuration一个 high performance Nginxserver, 用于processing high concurrent 静态filerequest and 反向proxyrequest:

# 全局configuration
user nginx;
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65536;

events {
    use epoll;
    worker_connections 10240;
    multi_accept on;
}

http {
    # basicconfiguration
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    
    # logconfiguration
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log warn;
    
    # performanceoptimizationconfiguration
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 100;
    client_max_body_size 10m;
    client_header_timeout 10s;
    client_body_timeout 10s;
    send_timeout 10s;
    
    # 压缩configuration
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
    
    # cacheconfiguration
    proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2 keys_zone=proxy_cache:10m max_size=10g inactive=60m use_temp_path=off;
    
    # serverconfiguration
    server {
        listen 80;
        server_name example.com;
        return 301 https://$host$request_uri;
    }
    
    server {
        listen 443 ssl http2;
        server_name example.com;
        
        # SSLconfiguration
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_prefer_server_ciphers on;
        ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
        ssl_session_tickets off;
        ssl_stapling on;
        ssl_stapling_verify on;
        resolver 8.8.8.8 8.8.4.4 valid=300s;
        resolver_timeout 5s;
        
        # 静态fileconfiguration
        root /var/www/example.com;
        index index.html;
        
        # 静态filecache
        location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|pdf|json)$ {
            expires 30d;
            add_header Cache-Control "public, max-age=2592000";
            add_header Last-Modified $date_gmt;
            if_modified_since off;
            etag off;
        }
        
        # proxyconfiguration
        location /api/ {
            proxy_pass http://backend;
            proxy_cache proxy_cache;
            proxy_cache_valid 200 30m;
            proxy_cache_valid 404 1m;
            proxy_cache_key "$scheme$request_method$host$request_uri";
            add_header X-Cache-Status $upstream_cache_status;
            
            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;
        }
        
        # statusmonitor
        location /nginx_status {
            stub_status on;
            access_log off;
            allow 127.0.0.1;
            allow 192.168.1.0/24;
            deny all;
        }
        
        # 主requestprocessing
        location / {
            try_files $uri $uri/ =404;
        }
    }
    
    #  on 游serverconfiguration
    upstream backend {
        server localhost:8080;
        server localhost:8081;
        least_conn;
    }
}

这个configurationpackage含了以 under performanceoptimization措施:

互动练习

1. 以 under 哪些 is Nginxperformanceoptimization important 措施? ( many 选)

A. optimization工作process数量
B. 启用 long 连接
C. 启用cache
D. 启用压缩
E. optimizationnetworkparameter

2. 以 under 哪个指令用于启用sendfile, reducingdata拷贝?

A. sendfile on
B. tcp_nopush on
C. tcp_nodelay on
D. directio on

3. 实践练习: configuration high performanceNginxserver

请configuration一个 high performance Nginxserver, 要求:

  • optimization工作processconfiguration, using many 核CPU
  • 启用epolleventmodel, improvingconcurrentprocessingcapacity
  • configuration long 连接, reducing连接建立 开销
  • 启用Gzip压缩, reducingnetwork传输量
  • for 静态file设置cache, reducing重复request
  • configurationSSL/TLSparameter, improvingsecurity性 and performance
  • 设置statusmonitor, 便于performanceanalysis and 调优

summarized and 展望

through本tutorial, 您已经Learning了Nginxperformanceoptimization coreparameter, configurationtechniques and best practices. performanceoptimization is a 持续 过程, 需要根据practicalcircumstancescontinuously调整 and optimization. 主要 performanceoptimization措施including:

in after 续 tutorialin, 我们将深入LearningNginx logmanagement and advanced主题, helping您全面MasterNginx usingtechniques.