basforge

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

    RU
    ConfigHomelabnginx

    Load balancing and failover in nginx: upstream, keepalive, and a 503 maintenance page

    Line-by-line load balancing configs: picking an algorithm, passive failover (max_fails and backup), backend keepalive pools, safe retries without duplicating POST requests, and toggling a 503 maintenance page via a flag file with no nginx reload.

    Balancing algorithms: which one to pick

    Inside an upstream block, nginx distributes requests using one of four algorithms:

    Directive Selection rule When to use
    (omitted) Round-robin, honoring weight Uniform fast requests (static assets, lightweight APIs)
    least_conn; Node with the fewest active connections Mix of fast and slow requests so one slow node doesn’t pile up a queue
    ip_hash; First three octets of client IPv4 (or full IPv6) App stores sessions in local memory; incompatible with backup
    hash $key consistent; Consistent hashing (e.g., on $arg_user or $request_uri) Distributed cache or sharding: losing a node remaps the fewest keys

    Every algorithm (except unweighted hash) accepts weight=N: weight=2 on node 1 and weight=1 on node 2 sends twice as many requests to node 1 (four out of every six).

    Ready config: upstream, keepalive, and safe retries

    A pool with two weighted primary nodes, one backup node, and a persistent keepalive connection pool.

    /etc/nginx/conf.d/pool.example.org.conf
    upstream app_pool {
        least_conn;
        server 10.0.0.11:8080 weight=2 max_fails=2 fail_timeout=10s;
        server 10.0.0.12:8080 weight=1 max_fails=2 fail_timeout=10s;
        server 10.0.0.13:8080 backup;
    Key part

    Declare upstream in the http context (outside server). least_conn routes each new request to the least busy node. max_fails=2 fail_timeout=10s runs passive health checks: two failures within 10 seconds pull the node out for 10 seconds before nginx probes it with one request. backup receives traffic only when every primary node is unavailable.

    default:weight 1max_fails 1fail_timeout 10s

        keepalive 16;
        keepalive_requests 1000;
        keepalive_timeout 60s;
    }
    Key part

    Idle TCP connection cache **per nginx worker** (4 workers × keepalive 16 = up to 64 open connections total). Each connection stays alive for up to 1000 requests or 60s idle, avoiding repeat TCP handshakes and TIME_WAIT buildup.

    default:keepalive_requests 1000keepalive_timeout 60s

    server {
        listen 80;
        server_name pool.example.org;
    
        location / {
            include snippets/proxy-headers.conf;
            proxy_set_header Connection "";
            proxy_pass http://app_pool;

    Include the shared header snippet from Reverse proxy (proxy_http_version 1.1 plus Host/X-Forwarded-*) and clear Connection to an empty string — without both directives, upstream keepalive won’t activate. proxy_pass points to the app_pool group name.

            proxy_next_upstream error timeout http_502 http_503 http_504;
            proxy_next_upstream_tries 3;
            proxy_next_upstream_timeout 10s;
        }
    }
    Key part

    Failover triggers: network error, timeout, or 502/503/504. proxy_next_upstream_tries 3 covers both primary nodes plus backup, while proxy_next_upstream_timeout 10s caps total retry duration at 10 seconds.

    default:proxy_next_upstream error timeoutproxy_next_upstream_tries 0 (all)proxy_next_upstream_timeout 0

    Open-source nginx health checks are passive: a node is marked down only after live requests fail (max_fails). To drain a node cleanly for maintenance with zero failed requests, mark it down temporarily and reload:

    server 10.0.0.11:8080 weight=2 down;

    Active background health checks (periodic /health probes by the proxy) aren’t in open-source nginx — they ship in commercial NGINX Plus, HAProxy, and Traefik.

    503 maintenance page without reloading nginx

    Editing configs and reverting them during a database migration or release adds extra steps. A cleaner pattern is a flag file on disk: creating an empty maintenance.on file switches the site to 503 with Retry-After right away; deleting the file restores traffic immediately.

    To let administrators verify the site during maintenance, list their IPs in a geo block (http context).

    /etc/nginx/conf.d/maintenance.example.org.conf
    geo $is_admin {
        default 0;
        203.0.113.50/32 1;
    }

    IP allowlist that keeps seeing the live site during maintenance (geo lives in the http context, outside server). Everyone else gets $is_admin = 0.

    server {
        listen 80;
        server_name pool.example.org;
    
        error_page 503 @maintenance;
    
        location / {
            set $maint 0;
            if (-f /var/www/maintenance.on) { set $maint 1; }
            if ($is_admin = 1) { set $maint 0; }
            if ($maint = 1) { return 503; }
    
            include snippets/proxy-headers.conf;
            proxy_set_header Connection "";
            proxy_pass http://app_pool;
        }
    Key part

    When /var/www/maintenance.on exists and the client isn’t allowlisted, return 503 so error_page 503 @maintenance; handles it. Keep any assets used by the page (logo, CSS) in a dedicated location or inline them inside maintenance.html.

        location @maintenance {
            root /var/www/errors;
            add_header Retry-After 300 always;
            rewrite ^ /maintenance.html break;
        }
    }
    Key part

    Named maintenance location: Retry-After: 300 tells clients and crawlers to retry in 5 minutes (always is required because 503 is an error status), and rewrite ^ /maintenance.html break; serves the page for any requested path while preserving status 503.

    Toggling maintenance mode takes a fraction of a second and needs no reload:

    sudo touch /var/www/maintenance.on    # return 503 to everyone except $is_admin
    sudo rm /var/www/maintenance.on       # restore normal traffic

    How to check

    1. Validate syntax and reload:
      sudo nginx -t && sudo systemctl reload nginx
    2. Verify weighted distribution (six requests against weight=2 and weight=1):
      for i in 1 2 3 4 5 6; do curl -s -H "Host: pool.example.org" http://127.0.0.1/; done | sort | uniq -c
      #   4 app1
      #   2 app2
    3. Confirm keepalive holds open ESTAB connections to backends:
      sudo ss -tnp '( dport = :8080 )' | grep ESTAB
      # ESTAB 0 0 10.0.0.10:46122 10.0.0.11:8080 users:(("nginx",pid=49180,fd=7))
    4. Stop the first backend and verify failover (with add_header X-Upstream $upstream_addr always; enabled temporarily in staging):
      curl -sD - -H "Host: pool.example.org" http://127.0.0.1/ | grep -iE '^(HTTP/|x-upstream)'
      # HTTP/1.1 200 OK
      # X-Upstream: 10.0.0.11:8080, 10.0.0.12:8080
    5. Test maintenance mode:
      sudo touch /var/www/maintenance.on
      curl -sI -H "Host: pool.example.org" http://127.0.0.1/any/path | grep -iE '^(HTTP/|retry-after)'
      # HTTP/1.1 503 Service Temporarily Unavailable
      # Retry-After: 300
      sudo rm /var/www/maintenance.on

    If it doesn’t work

    You added keepalive 32; to upstream, yet TIME_WAIT sockets climb under load and backends see a new connection per request

    Cause
    The location block still proxies over HTTP/1.0 with Connection: close (nginx’s default), so the keepalive pool goes unused.
    Fix
    Include both lines in location: proxy_http_version 1.1; (already in snippets/proxy-headers.conf) and proxy_set_header Connection "";.

    Both primary nodes went down, yet backup never answered — clients got 502 with X-Upstream: 10.0.0.11:8101, 10.0.0.12:8102

    Cause
    proxy_next_upstream_tries 2; spent both attempts on the two dead primary nodes, so nginx never tried the third (backup) node.
    Fix
    Set proxy_next_upstream_tries to at least the total node count including backup (or 0 for unlimited attempts, capping total time via proxy_next_upstream_timeout).

    During occasional backend timeouts, orders or payments started getting created twice

    Cause
    non_idempotent was added to proxy_next_upstream, making nginx replay a POST on a second node while the first was still committing to the database.
    Fix
    Remove non_idempotent from proxy_next_upstream: without it, nginx retries only safe methods (GET, HEAD, OPTIONS) and never duplicates POST or PATCH.

    You served a maintenance page with 200 OK, and search engines replaced page titles with the maintenance notice

    Cause
    Crawlers treated 200 as updated site content and re-indexed the placeholder.
    Fix
    Always return 503 Service Unavailable with a Retry-After header (in seconds) so crawlers treat the downtime as temporary and keep existing rankings.

    During a planned backend update, some clients hit 502 before the node reaches max_fails

    Cause
    The backend stopped while nginx was still routing traffic to it; non-idempotent POST requests that landed on it first won’t retry on another node.
    Fix
    Mark the server down; in upstream, run sudo nginx -t && sudo systemctl reload nginx, update the backend, remove down;, and reload again.