Nginx负载均衡策略需求:分区域固定主备服务器转发流量
Hey there! That massive weight workaround you're using does technically get the job done, but you’re totally right—it’s not the clean or intended way to set up primary/backup failover in Nginx. Luckily, there’s a built-in, standard directive made exactly for this scenario: backup.
How It Works
The backup flag tells Nginx to only send traffic to that server if all non-backup servers are unavailable. This aligns perfectly with your requirement: keep 100% of traffic on the primary server when it’s healthy, and switch to the backup only when the primary fails.
Revised Configuration
Here’s how to rewrite your upstreams using the proper backup parameter, while keeping your existing session persistence with ip_hash:
upstream US_UPSTREAM { ip_hash; # Primary server: handles all traffic when healthy server 2.2.2.2 max_fails=10 fail_timeout=3600s; # Backup server: only used if primary is marked down server 1.1.1.1 backup; } upstream EU_UPSTREAM { ip_hash; # Primary server for EU region server 1.1.1.1 max_fails=10 fail_timeout=3600s; # Backup server for EU region server 2.2.2.2 backup; }
Key Details to Keep in Mind
ip_hashcompatibility: Yourip_hashdirective works seamlessly withbackup—users will stick to the same server (primary or backup) as long as their IP stays consistent, preserving session persistence.- Failover thresholds: Your current
max_fails=10andfail_timeout=3600smean Nginx will mark the primary as down after 10 failed connection attempts, and keep it marked down for an hour. Adjust these values if you want faster/slower failover (e.g.,max_fails=3 fail_timeout=30sfor quicker fault detection). - Explicit intent: Unlike the massive weight hack, this configuration makes your primary/backup relationship crystal clear—anyone reading the config will immediately understand your traffic routing strategy, making maintenance way easier.
Testing the Failover
To confirm it works as expected:
- Stop the primary server for a region.
- Send traffic to that upstream—you’ll see it route exclusively to the backup server.
- Restart the primary server; after the
fail_timeoutperiod elapses, Nginx will automatically shift traffic back to the primary.
内容的提问来源于stack exchange,提问作者ace

