Operations 11 min read

Boost Your Nginx Performance: Proven Configuration & Tuning Secrets

This article walks through practical Nginx performance tuning—optimizing worker processes, expanding connection limits, enabling caching and gzip, adjusting kernel parameters, and providing a one‑click diagnostic script—backed by real benchmark data that shows up to five‑fold improvements in concurrency and response times.

Ops Community
Ops Community
Ops Community
Boost Your Nginx Performance: Proven Configuration & Tuning Secrets

Nginx Practical Tips: High‑Performance Web Server Configuration and Optimization

Opening: Is Your Nginx Fully Utilizing Its Performance?

Scenario: At 5 pm on a Friday, operations reports “the website is slow, pages take 10 seconds”. top shows only 30 % CPU usage, plenty of memory, but netstat -anp | grep :80 | wc -l reveals over 5 000 connections and the error log contains “worker_connections are not enough”.

This situation is common: even on an 8‑core 16 GB server, Nginx behaves like a starving engine.

In this article I share five years of production experience, covering worker process optimization, connection limits, cache acceleration, and kernel parameter tuning, each backed by real benchmark data. After applying these settings, concurrency increases 3‑5× and response time drops more than 50 %.

1. Worker Process Optimization – Squeeze Every CPU Core

1.1 Core Setting: How Many worker_processes?

Many set worker_processes 4; and waste half of an 8‑core machine.

Correct configuration:

# Method 1: Auto‑detect CPU cores (recommended)
worker_processes auto;

# Method 2: Manually set to core count
worker_processes 8;

# Method 3: For CPU‑intensive workloads, 1.5‑2× cores
worker_processes 16;

Key command: Check CPU cores

grep -c ^processor /proc/cpuinfo
# or
nproc

1.2 CPU Affinity – Prevent Frequent Context Switching

By default Nginx workers jump between cores, reducing CPU cache hit rate.

Optimization:

# Example for 8‑core server
worker_processes 8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
# Simplified (Nginx 1.9.10+)
worker_cpu_affinity auto;

Real‑world test on an e‑commerce site shows a 12 % QPS increase and 30 % reduction in latency jitter.

1.3 Pitfall: worker_rlimit_nofile Must Be Set

When concurrency spikes, logs show “Too many open files” even though ulimit -n is 65535.

Reason: The master process limit does not propagate to workers.

Solution:

# Place at top of nginx.conf
worker_rlimit_nofile 65535;

events {
    worker_connections 10240;
    use epoll;
}

2. Breaking Connection Limits – From 1 024 to 100 000 Concurrent Connections

2.1 Kernel Parameter Tuning (Critical)

Most only tweak Nginx config and ignore the Linux kernel bottleneck.

Create optimization script:

/etc/sysctl.d/nginx-optimize.conf
# TCP connection queue
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 8192

# TIME_WAIT optimization (critical)
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 0   # Do NOT enable in NAT
net.ipv4.tcp_fin_timeout = 30

# Port range
net.ipv4.ip_local_port_range = 1024 65535

# File handles
fs.file-max = 1000000

# Apply immediately
sysctl -p /etc/sysctl.d/nginx-optimize.conf

Avoid: tcp_tw_recycle in NAT environments (e.g., behind Alibaba Cloud SLB).

2.2 Nginx Connection Configuration

events {
    worker_connections 10240;
    multi_accept on;
    accept_mutex off;
}
http {
    keepalive_timeout 65;
    keepalive_requests 100;
    client_body_timeout 10;
    client_header_timeout 10;
    send_timeout 10;
}

Formula: Max concurrency = worker_processes × worker_connections ÷ 2 (for reverse proxy).

3. Cache Acceleration – Keep 80 % of Requests Off the Backend

3.1 FastCGI Cache for PHP

# Define cache path
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=FASTCGI:100m inactive=60m max_size=1g;

server {
    location ~ \.(php)$ {
        fastcgi_cache FASTCGI;
        fastcgi_cache_key "$scheme$request_method$host$request_uri";
        fastcgi_cache_valid 200 60m;
        fastcgi_cache_valid 404 10m;
        add_header X-Cache-Status $upstream_cache_status;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

3.2 Static File Cache & Gzip Compression

http {
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml+rss;
    gzip_comp_level 6;

    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2?)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
        access_log off;
    }
}

Benchmarks on a news site show a 70 % reduction in server load and 2.5× faster page loads.

4. Practical Script – One‑Click Nginx Performance Diagnosis

Save as nginx_performance_check.sh and run to check worker count, connection stats, file‑handle limits, recent errors, and receive optimization suggestions.

#!/bin/bash
# Nginx performance diagnostic script v1.0
# Usage: bash nginx_performance_check.sh
...

5. Load Test Verification – Before and After

Using wrk (1000 concurrent connections for 30 seconds) the following improvements were observed:

QPS increased from 3,200 to 15,600 (+387 %).

Average response time dropped from 312 ms to 64 ms (‑79 %).

99 % latency reduced from 1,850 ms to 210 ms (‑88 %).

Error rate fell from 2.3 % to 0.01 % (‑99 %).

Conclusion – Five‑Minute Configuration, Five‑Fold Performance Gain

By mastering these Nginx tuning methods you can:

Worker optimization – increase CPU utilization by 30 %.

Connection breakthrough – support 100 k concurrent users.

Cache acceleration – keep 80 % of requests from hitting the backend.

Kernel tuning – eliminate TIME_WAIT buildup.

Always test configuration syntax with nginx -t and reload gracefully with nginx -s reload to avoid service disruption.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

performanceConfigurationcachingLinuxLoad TestingNGINXWeb serverTuning
Ops Community
Written by

Ops Community

A leading IT operations community where professionals share and grow together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.