bashadvanced

Nginx Load Balancer Configuration

Nginx upstream load balancer with weighted round-robin, health checks, and failover handling.

bash
# /etc/nginx/nginx.conf
worker_processes auto;
events {
    worker_connections 4096;
    multi_accept on;
}

http {
    upstream app_cluster {
        least_conn;

        server 10.0.1.10:3000 weight=5;
        server 10.0.1.11:3000 weight=3;
        server 10.0.1.12:3000 weight=2;
        server 10.0.1.13:3000 backup;

        keepalive 32;
    }

    # Rate limiting zone
    limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;

    server {
        listen 80;
        server_name app.example.com;

        location / {
            proxy_pass http://app_cluster;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            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_connect_timeout 5s;
            proxy_send_timeout 30s;
            proxy_read_timeout 30s;

            proxy_next_upstream error timeout http_502 http_503;
            proxy_next_upstream_tries 3;
        }

        location /api/ {
            limit_req zone=api burst=20 nodelay;
            proxy_pass http://app_cluster;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
        }

        location /health {
            access_log off;
            return 200 'ok';
            add_header Content-Type text/plain;
        }
    }
}

Use Cases

  • Distributing traffic across multiple app servers
  • High-availability web service deployment
  • API rate limiting at the load balancer layer

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.