basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ConfigHomelabnginx

    Tuning nginx: workers, networking, buffers, Gzip, and Brotli

    Configure worker_processes, open file descriptor limits (worker_rlimit_nofile), kernel flags (sendfile/tcp_nopush/tcp_nodelay), open_file_cache, gzip with gzip_static, Brotli, and proxy buffering.

    Workers and open file descriptor limits

    A single nginx worker handles thousands of concurrent connections, yet in practice it hits two caps early: worker_connections (per-worker socket limit) and the OS open-file limit (ulimit -n).

    As a reverse proxy, each client connection uses two descriptors: one incoming socket from the browser and one outgoing socket to the app. With worker_connections 4096, a worker serves roughly 2,000 concurrent proxied clients, so set worker_rlimit_nofile with at least 2x headroom:

    # /etc/nginx/nginx.conf — top-level main context
    user nginx;
    worker_processes auto;
    worker_rlimit_nofile 16384;
    
    events {
        worker_connections 4096;
    }

    worker_rlimit_nofile raises the open-file ceiling for nginx itself without editing limits.conf or the systemd unit (provided master starts as root).

    Network stack: sendfile, tcp_nopush, tcp_nodelay, and open_file_cache

    Four directives in the http context cut unnecessary data copies and syscalls when serving static files:

    /etc/nginx/conf.d/04-performance.conf
    sendfile    on;
    tcp_nopush  on;
    tcp_nodelay on;

    sendfile on copies static files straight from the kernel page cache to the network socket without passing through nginx user-space memory. tcp_nopush on (only active with sendfile) enables TCP_CORK so HTTP headers and the start of the file go out in one full TCP packet. tcp_nodelay on disables Nagle’s algorithm for short interactive frames (WebSocket, SSE, keep-alive). They work together without conflict: tcp_nopush applies while sending the file, and tcp_nodelay takes over on the final packet.

    default:sendfile offtcp_nopush offtcp_nodelay on

    open_file_cache          max=2000 inactive=30s;
    open_file_cache_valid    60s;
    open_file_cache_min_uses 2;
    open_file_cache_errors   on;
    Key part

    Caches open file descriptors and metadata (stat, size, modification time, and file-not-found errors). Removes thousands of repeated disk lookups under heavy static traffic. If static files are overwritten in place frequently, keep open_file_cache_valid short (30–60 s).

    default:open_file_cache off

    Compression: Gzip, gzip_static, and Brotli

    Text formats (HTML, CSS, JS, JSON, SVG) shrink 3–5x. Never add already-compressed formats (JPEG, PNG, WebP, AVIF, WOFF2, MP4, ZIP) to gzip_types — re-compressing them wastes CPU and can even add a few bytes.

    /etc/nginx/conf.d/05-compression.conf
    gzip on;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_vary on;
    gzip_proxied any;
    gzip_types
        text/plain
        text/css
        text/xml
        application/javascript
        application/json
        application/xml
        image/svg+xml;
    Key part

    On-the-fly compression. Level 5 balances ratio against CPU time. gzip_min_length 1024 skips tiny responses under 1 KB. gzip_vary on adds Vary: Accept-Encoding so proxies and CDNs don’t serve compressed bodies to clients that lack gzip support. gzip_proxied any compresses responses even when requests arrive through an upstream proxy.

    default:gzip offgzip_comp_level 1gzip_min_length 20gzip_vary off

    gzip_static on;
    Key part

    Serves pre-compressed files (--with-http_gzip_static_module is compiled into the nginx.org package). When app.js.gz sits next to app.js (built in CI at compression level 9), nginx streams the .gz file straight via sendfile at zero CPU cost.

    default:gzip_static off

    What about Brotli

    Brotli compresses text 15–20% smaller than Gzip, though the default nginx.org build omits ngx_brotli. You have two options:

    • If Cloudflare or another CDN sits in front of your server, it compresses responses to Brotli at the edge — no nginx module needed.
    • On a direct origin server, install the dynamic ngx_brotli module (Ubuntu 24.04 and 26.04 ship libnginx-mod-http-brotli-filter and libnginx-mod-http-brotli-static for the distro package; for nginx.org, compile the module against your exact 1.30.x version or use a third-party package). Once loaded, enable brotli on; brotli_comp_level 5; brotli_static on;.

    Proxy buffering: when it helps and when to turn it off

    By default nginx enables both backend response buffering (proxy_buffering on) and incoming request body buffering (proxy_request_buffering on).

    Directive Why it’s on by default When to disable (off)
    proxy_buffering The backend dumps the response into nginx memory and frees its worker right away while nginx trickles bytes to a slow mobile client Streaming responses: SSE, AI chat streams, live logs (Reverse proxy)
    proxy_request_buffering nginx absorbs a slow client upload first and hands it to the backend all at once, shielding the app from Slowloris Multi-gigabyte uploads that would otherwise fill /var/cache/nginx/client_temp on disk

    For a standard API returning large JSON payloads, raise the in-memory buffers instead of disabling buffering so responses don’t spill to disk:

    proxy_buffers 16 16k;          # 16 buffers of 16 KB (256 KB per connection)
    proxy_buffer_size 16k;         # buffer for the first part of the response (headers)
    proxy_busy_buffers_size 32k;

    How to check

    1. Validate and reload the config:
      sudo nginx -t && sudo systemctl reload nginx
    2. Verify that the worker’s active open-file limit went up:
      grep 'Max open files' /proc/$(pgrep -o -f 'nginx: worker')/limits
      # Max open files            16384                16384                files
    3. Verify gzip and gzip_static (after creating big.txt.gz next to big.txt, Content-Length should match the .gz file size on disk):
      curl -sI -H "Accept-Encoding: gzip" https://example.org/static/big.txt \
        | grep -iE '^(HTTP/|content-encoding|vary|content-length)'
      # HTTP/1.1 200 OK
      # Content-Length: 77
      # Vary: Accept-Encoding
      # Content-Encoding: gzip

    If it doesn’t work

    Under load, /var/log/nginx/error.log fills with worker_connections are not enough or accept4() failed (24: Too many open files)

    Cause
    Concurrent sockets hit worker_connections (default 1024) or the OS open-file limit (nofile). In reverse-proxy mode each client consumes at least two descriptors: one socket to the browser and one to the backend.
    Fix
    Raise worker_connections 4096; inside events {} and set worker_rlimit_nofile 16384; in the top-level nginx.conf context (at least worker_connections * 2, plus headroom for logs and static files).

    gzip on; is set, yet .css, .js, and JSON responses arrive without Content-Encoding: gzip

    Cause
    By default gzip_types includes only text/html. Other MIME types must be listed explicitly, and responses smaller than gzip_min_length are never compressed.
    Fix
    Add gzip_types text/plain text/css application/javascript application/json image/svg+xml application/xml; and test with curl -sI -H "Accept-Encoding: gzip".

    Uploading 100 MB files through the proxy fills /var/cache/nginx/client_temp and logs a client request body is buffered to a temporary file

    Cause
    The request body exceeds client_body_buffer_size (8–16 KB by default), so nginx writes it to a temporary file on disk before forwarding it to the backend.
    Fix
    On large-upload routes (such as an S3 gateway or media server), stream bodies directly without disk buffering: proxy_request_buffering off;.

    Setting gzip_comp_level 9 multiplied CPU load with almost no size reduction

    Cause
    Levels 5 and 9 differ by a fraction of a percent in output size, while CPU cost grows several times on every response.
    Fix
    Keep gzip_comp_level 5; (or 6) for on-the-fly compression, and pre-compress static assets at level 9 during the build for gzip_static on;.

    Adding brotli on; makes nginx -t fail with unknown directive "brotli"

    Cause
    The official nginx.org package does not compile ngx_brotli in by default.
    Fix
    Load the dynamic modules (load_module modules/ngx_http_brotli_filter_module.so; and ngx_http_brotli_static_module.so;) built for your exact nginx version, or stick with gzip + gzip_static (if Cloudflare sits in front, it already compresses responses with Brotli).