DEV Community

Schiff Heimlich
Schiff Heimlich

Posted on

nginx resolves upstreams once at startup — unless you tell it not to

You configure an upstream with a hostname. nginx starts, resolves it, caches the IP. Three weeks later the load balancer fails over to a new IP. Your nginx keeps sending traffic to the old one until you reload.

This catches everyone once.

The fix is two lines:

resolver 127.0.0.11 valid=10s;
set $upstream http://my-service.internal;
proxy_pass $upstream;
Enter fullscreen mode Exit fullscreen mode

127.0.0.11 is Docker's embedded DNS. If you're not in Docker, use your actual resolver (often 8.8.8.8 or your VPC's DNS). The valid=10s means nginx re-resolves every 10 seconds.

The set $upstream variable is the trick — nginx only re-resolves when the proxy_pass value is a variable. Hardcoded hostnames in proxy_pass don't trigger re-resolution.

If you're using the resolve parameter (nginx 1.19+):

resolver 127.0.0.11 valid=10s;
proxy_pass http://my-service.internal resolve;
Enter fullscreen mode Exit fullscreen mode

That's it. No variable needed. The resolve flag tells nginx to honor the TTL and re-resolve.

Debugging tip: strace -p $(pidof nginx) -e trace=network -s 100 shows the DNS queries in real time. You'll see the A/AAAA requests going out on the resolver interval.

One gotcha: if the resolver goes down, nginx returns 502. Add a fallback:

resolver 127.0.0.11 8.8.8.8 valid=10s ipv6=off;
Enter fullscreen mode Exit fullscreen mode

That's the whole thing. Two lines (or one with resolve) and your upstream DNS changes actually propagate.

Top comments (0)