How to Set Backup Server in Nginx for Load Balancing
To set a backup server in
nginx, define multiple server entries inside an upstream block and mark the backup server with the backup parameter. Nginx will send traffic to the backup server only if all primary servers are down.Syntax
The upstream block groups backend servers for load balancing. Each server directive inside it defines a backend server. Adding the backup parameter to a server marks it as a fallback server used only when all primary servers fail.
upstream <name> { ... }: Defines a group of backend servers.server <address> [parameters];: Defines a backend server with optional parameters.backup: Marks the server as a backup/failover server.
nginx
upstream backend {
server primary1.example.com;
server primary2.example.com;
server backup.example.com backup;
}Example
This example shows how to configure Nginx to load balance between two primary servers and use a backup server only if both primaries are unavailable.
nginx
http {
upstream backend {
server 192.168.1.10;
server 192.168.1.11;
server 192.168.1.20 backup;
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}
}Output
Nginx will send requests to 192.168.1.10 and 192.168.1.11 normally. If both are down, it will send requests to 192.168.1.20 as a backup.
Common Pitfalls
- Forgetting to add the
backupparameter causes the server to be treated as a normal load balancer, not a fallback. - Placing the backup server before primary servers can cause unexpected behavior; always list primary servers first.
- Not testing failover scenarios can leave your backup server unused or misconfigured.
nginx
upstream backend {
# Wrong: backup server without 'backup' keyword
server 192.168.1.20;
server 192.168.1.10;
server 192.168.1.11;
}
# Correct:
upstream backend {
server 192.168.1.10;
server 192.168.1.11;
server 192.168.1.20 backup;
}Quick Reference
Use the backup parameter inside upstream to set a backup server. Primary servers handle traffic normally. Backup servers only receive traffic if all primaries fail.
- upstream: Group backend servers.
- server: Define each backend server.
- backup: Mark server as fallback.
| Directive | Purpose |
|---|---|
| upstream | Defines a group of backend servers for load balancing |
| server | Specifies a backend server address and options |
| backup | Marks a server as a backup used only if primaries fail |
Key Takeaways
Use the 'backup' parameter in the 'server' directive inside 'upstream' to set a backup server.
List primary servers first and backup servers last in the 'upstream' block.
Backup servers only receive traffic when all primary servers are unavailable.
Test failover to ensure backup servers work as expected.
Properly configure proxy_pass to point to the upstream group.