Sub topic 6
Grouping backends with upstream
This chapter assumes you can already write a server block that uses proxy_pass to reach one backend. It also assumes you know how to run nginx -t and reload the configuration. Here you replace the single backend address with a named group of servers. The next chapters build on that group with load-balancing methods and failure handling.
Why a named group
With proxy_pass http://127.0.0.1:3000; the backend address is written into the location. That is fine for one server. Once you have two or more copies of the application, you need one place to list them. Nginx provides that place in the upstream block.
An upstream block does three things:
- It gives a set of backend servers a single name.
- It holds the settings that belong to the group as a whole, such as the balancing method and keepalive connections.
- It holds the settings that belong to each member, such as weight and failure limits.
A location then refers to the group by name in proxy_pass. Several locations, or even several server blocks, can share one group.
A first upstream group
The upstream block belongs in the http context. It must not appear inside a server or location block. On Debian and Ubuntu, files in /etc/nginx/conf.d/ and /etc/nginx/sites-enabled/ are included inside http, so you can place it at the top level of one of those files.
upstream app_backend {
server 10.0.0.11:8080;
server 10.0.0.12:8080;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://app_backend;
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_set_header X-Forwarded-Proto $scheme;
}
}Check and apply it:
sudo nginx -t && sudo systemctl reload nginxWith no other directives, Nginx uses round robin. It sends the first request to the first server, the second to the second, and so on in a cycle. To see this, have each backend return its own name, then run:
for i in 1 2 3 4; do curl -s http://example.com/whoami; echo; doneYou should see the two backends alternate.
How the name in proxy_pass is read
When Nginx parses proxy_pass http://app_backend;, it first checks whether app_backend matches an upstream block name. If it does, it uses the group. If not, it treats the name as a host name and resolves it through DNS. A misspelled group name therefore fails in a confusing way. You get an error such as host not found in upstream "app_backend" from nginx -t, because Nginx tried DNS and found nothing.
The same rule explains why group names should not look like real host names you might want to reach. Choose names such as app_backend or api_pool.
The Host header trap
Inside a location that uses proxy_pass, Nginx's default Host header sent to the backend is $proxy_host. That variable holds the name or address written in proxy_pass. With an upstream group, the backend would receive Host: app_backend, which no application expects.
Always add proxy_set_header Host $host; when proxying to a group. Without it, virtual-host routing on the backend, generated absolute URLs and cookie domains can all break. The cause is not obvious from the symptom, so check this first when a backend behaves differently behind Nginx than when you call it directly.
Server parameters
Each server line in an upstream accepts an address followed by optional parameters. The address can be an IP with a port, a host name with a port, or a Unix socket written as unix:/path/to/socket. If you omit the port, Nginx uses port 80.
| Parameter | Meaning | Default |
|---|---|---|
| `weight=N` | Relative share of requests this server receives | 1 |
| `max_fails=N` | Failed attempts within `fail_timeout` before the server is considered unavailable | 1 |
| `fail_timeout=T` | The window for counting failures, and also how long the server is then skipped | 10s |
| `max_conns=N` | Maximum simultaneous connections to this server; 0 means no limit | 0 |
| `backup` | Receives traffic only when all non-backup servers are unavailable | off |
| `down` | Marks the server as permanently unavailable | off |
The chapters on balancing and passive health checks cover weight, max_fails, fail_timeout and backup in detail. This chapter only needs you to recognize them in a group definition.
The down parameter deserves attention now, because it is the simplest way to take a server out of rotation for maintenance. Add down to the line, run nginx -t, and reload. Existing requests finish, and new ones go elsewhere.
upstream app_backend {
zone app_backend 64k;
server 10.0.0.11:8080 weight=2;
server 10.0.0.12:8080 max_conns=100;
server 10.0.0.14:8080 down;
server unix:/run/app/app.sock;
}The zone directive puts the group's state in shared memory. Without it, each Nginx worker process keeps its own copy of counters such as failure counts and max_conns usage. With it, all workers share one view. If you rely on max_conns or on accurate failure tracking, add a zone.
Host names, DNS and when they are resolved
You can write a host name instead of an IP address:
upstream app_backend {
server app1.internal.example:8080;
server app2.internal.example:8080;
}Nginx resolves these names once, while it reads the configuration at start or reload. It does not look them up again at request time. If app1.internal.example later points to a new address, Nginx keeps using the old one until the next reload. If the name cannot be resolved at startup, Nginx refuses to load the configuration.
Two practical consequences follow:
- Use stable IP addresses or names from
/etc/hostswhen the backends are on fixed machines. - If your backends are behind changing DNS records, plan to reload Nginx when they change. Alternatively, use a mechanism designed for dynamic resolution, which is outside this chapter.
A host name that resolves to several addresses expands into several servers in the group, each with the parameters you gave. Only the first parameters line applies to all of them.
Using a group from more than one place
A group is a shared definition. Two applications can use different groups, and one group can serve several locations.
upstream web_pool {
server 10.0.0.11:8080;
server 10.0.0.12:8080;
}
upstream api_pool {
server 10.0.0.21:9000;
server 10.0.0.22:9000;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://web_pool;
proxy_set_header Host $host;
}
location /api/ {
proxy_pass http://api_pool;
proxy_set_header Host $host;
}
}Because proxy_pass here has no URI part after the group name, Nginx passes the request path unchanged. If you add a path, such as http://api_pool/v2/, the matched location prefix is replaced. The earlier chapter on URI handling covers that rule, and it applies to groups exactly as it does to single addresses.
A group name can also be used through a variable, but then Nginx must decide at request time whether the value is a group. If proxy_pass contains a variable, Nginx still checks upstream names first. Only when none matches does it use the resolver. This is a common source of confusion, so test any variable-based proxy_pass carefully.
Choosing HTTP or HTTPS to the group
The scheme in proxy_pass applies to every member of the group. If you write proxy_pass https://app_backend;, Nginx connects to every server in the group with TLS. You cannot mix plain and encrypted backends in one group. If some backends speak HTTPS and others HTTP, create two groups.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `"upstream" directive is not allowed here` | The block is inside `server` or `location` | Move it to the `http` context |
| `host not found in upstream "name"` | The group name is misspelled, or a server host name does not resolve | Check the spelling and the DNS or `/etc/hosts` entry |
| Backend sees `Host: app_backend` | `Host` header not set | Add `proxy_set_header Host $host;` |
| Traffic goes to an old address after a DNS change | Names are resolved only at reload | Reload Nginx, or use fixed IPs |
| `max_conns` seems ignored across workers | No shared memory zone | Add `zone name size;` to the group |
| `duplicate upstream "app_backend"` | Two blocks share a name | Rename one of them |
Checking the result
After any change, validate before you reload, and then test from the outside:
- Run
sudo nginx -tand read any error with its file name and line number. - Run
sudo systemctl reload nginx, which applies the change without dropping connections. - Send several requests with
curland confirm that each backend receives some of them. - Look at
/var/log/nginx/error.logfor lines mentioningupstream.
Exercise
You define upstream app_backend { server 10.0.0.11:8080; server 10.0.0.12:8080; } and use proxy_pass http://app_backend; in a location with no other proxy settings. The backends serve different sites based on the Host header, and they now return the wrong site. What is the cause and the fix?
Show answer
Nginx sends Host: app_backend by default, because it uses $proxy_host, the name written in proxy_pass. Add proxy_set_header Host $host; to the location so the backends receive the original host name the client requested. Then run sudo nginx -t && sudo systemctl reload nginx.
Exercise
A backend is listed as server app1.internal.example:8080; in an upstream group. The DNS record for that name changes to a new IP address. Why does Nginx keep sending traffic to the old address, and how do you make it use the new one?
Show answer
Nginx resolves host names in upstream server lines only when it reads the configuration at start or reload. Reload Nginx with sudo systemctl reload nginx so it resolves the name again. To avoid this, use fixed IP addresses or reload whenever the record changes.