乐闻世界logo
搜索文章和话题

How to perform Nginx performance tuning? What are the key parameters?

2月21日 16:57

How to perform Nginx performance tuning? What are the key parameters?

Nginx performance tuning is a systematic engineering task that requires optimization from multiple dimensions. Proper configuration can significantly improve Nginx's processing capability and response speed.

Core Configuration Optimization:

nginx
# Global configuration user nginx; worker_processes auto; # Automatically set to CPU core count worker_rlimit_nofile 100000; # File descriptor limit worker_cpu_affinity auto; # CPU affinity binding events { worker_connections 65535; # Maximum connections per worker use epoll; # Use epoll on Linux multi_accept on; # Accept multiple connections simultaneously accept_mutex off; # Disable mutex lock to reduce lock contention } http { # Basic optimization sendfile on; # Enable efficient file transfer tcp_nopush on; # Optimize packet sending tcp_nodelay on; # Disable Nagle's algorithm keepalive_timeout 65; # Keep-alive timeout keepalive_requests 100; # Maximum requests per keep-alive connection # Buffer optimization client_body_buffer_size 128k; # Client request body buffer client_max_body_size 10m; # Maximum request body size client_header_buffer_size 1k; # Client request header buffer large_client_header_buffers 4 4k; # Large request header buffer # Output buffering output_buffers 1 32k; # Output buffer postpone_output 1460; # Delay output # File cache open_file_cache max=100000 inactive=20s; # File descriptor cache open_file_cache_valid 30s; # Cache validation interval open_file_cache_min_uses 2; # Minimum usage count open_file_cache_errors on; # Cache error information # Gzip compression gzip on; gzip_vary on; gzip_min_length 1024; gzip_comp_level 6; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss; gzip_disable "msie6"; }

Worker Process Optimization:

nginx
# Set based on CPU core count worker_processes auto; # Bind CPU cores (manual setting) # Assuming 4-core CPU worker_processes 4; worker_cpu_affinity 0001 0010 0100 1000; # Set worker process priority worker_priority -5; # -20 to 19, lower value means higher priority

Connection Optimization:

nginx
events { # Increase connection count worker_connections 65535; # Accept multiple connections simultaneously multi_accept on; # Disable mutex lock (for high concurrency) accept_mutex off; # Use efficient event model use epoll; # Linux # use kqueue; # BSD/macOS } http { # Keep-alive optimization keepalive_timeout 65; keepalive_requests 100; # Upstream server keep-alive upstream backend { server 192.168.1.100:8080; keepalive 32; # Keep 32 idle connections } # Proxy timeout settings proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; }

Buffer Optimization:

nginx
http { # Client buffers client_body_buffer_size 128k; client_max_body_size 10m; client_header_buffer_size 1k; large_client_header_buffers 4 4k; # Proxy buffers proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 4k; proxy_busy_buffers_size 8k; # FastCGI buffers fastcgi_buffer_size 4k; fastcgi_buffers 8 4k; # Output buffers output_buffers 1 32k; postpone_output 1460; }

File Operation Optimization:

nginx
http { # File cache open_file_cache max=100000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on; # Efficient file transfer sendfile on; tcp_nopush on; tcp_nodelay on; # Direct I/O (for large files) # directio 4m; }

Compression Optimization:

nginx
http { gzip on; gzip_vary on; gzip_min_length 1024; # Minimum file size to compress gzip_comp_level 6; # Compression level 1-9 gzip_buffers 16 8k; # Compression buffers gzip_http_version 1.1; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/rss+xml application/atom+xml image/svg+xml; gzip_disable "msie6"; # Static resource pre-compression gzip_static on; }

Log Optimization:

nginx
http { # Custom log format log_format main '$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"'; # Access log access_log /var/log/nginx/access.log main buffer=32k flush=5s; # Error log error_log /var/log/nginx/error.log warn; # Disable static resource logging location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2)$ { access_log off; } }

SSL/TLS Optimization:

nginx
server { listen 443 ssl http2; # SSL session cache ssl_session_cache shared:SSL:50m; ssl_session_timeout 1d; ssl_session_tickets off; # SSL buffers ssl_buffer_size 4k; # Protocols and cipher suites ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256; ssl_prefer_server_ciphers on; # OCSP Stapling ssl_stapling on; ssl_stapling_verify on; }

System-Level Optimization:

bash
# /etc/sysctl.conf # File descriptors fs.file-max = 1000000 # TCP parameters net.ipv4.tcp_max_tw_buckets = 6000 net.ipv4.tcp_sack = 1 net.ipv4.tcp_window_scaling = 1 net.ipv4.tcp_rmem = 4096 87380 4194304 net.ipv4.tcp_wmem = 4096 65536 4194304 net.core.rmem_max = 16777216 net.core.wmem_max = 16777216 net.core.netdev_max_backlog = 262144 net.ipv4.tcp_max_syn_backlog = 262144 net.ipv4.tcp_fin_timeout = 30 net.ipv4.tcp_keepalive_time = 1200 net.ipv4.tcp_tw_reuse = 1 # Apply configuration sysctl -p

User Limits:

bash
# /etc/security/limits.conf nginx soft nofile 65535 nginx hard nofile 65535

Monitoring and Diagnostics:

nginx
# Status monitoring location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } # Request tracing location /debug { add_header X-Request-ID $request_id; add_header X-Upstream-Addr $upstream_addr; }

Performance Testing Tools:

bash
# wrk stress test wrk -t12 -c4000 -d30s http://example.com/ # ab stress test ab -n 10000 -c 1000 http://example.com/ # siege stress test siege -c 100 -t 60S http://example.com/

Key Performance Metrics:

  1. QPS (Queries Per Second): Measure processing capability
  2. Response Time: Average, P95, P99
  3. Concurrent Connections: Current active connections
  4. Error Rate: Ratio of 4xx, 5xx errors
  5. CPU Usage: Should not consistently exceed 70%
  6. Memory Usage: Monitor memory consumption
  7. Disk I/O: Monitor read/write performance

Tuning Recommendations:

  1. Gradual tuning: Adjust only one parameter at a time, observe results
  2. Benchmarking: Perform performance comparison before and after tuning
  3. Monitor metrics: Continuously monitor key performance indicators
  4. Log analysis: Analyze access logs to identify bottlenecks
  5. Regular review: Periodically check if configuration is reasonable
标签:Nginx