brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: the resolve parameter keeps nginx starting when a container name does not resolve yet

Nginx
~/tips/tip-nginx-upstream-resolve-docker

upstream app {

Looks up upstream host names at run time so nginx starts even when a backend is missing.

nginx resolves host names in proxy_pass once, at startup. When a container behind it is not running yet, nginx refuses to start with host not found in upstream, and then every other site on it is down too.

Since nginx 1.27.3 the open source version can resolve upstream names at run time:

upstream app {
    zone app 64k;
    resolver 127.0.0.11 valid=30s;
    server myapp:3000 resolve;
}
server {
    location / { proxy_pass http://app; }
}

127.0.0.11 is Docker’s built-in DNS on user-defined networks. The zone line is required: without it nginx -t says the upstream must be in shared memory. With myapp missing, nginx starts and answers 502 for that site instead of failing as a whole; the plain proxy_pass http://myapp:3000 version does not start at all. I like that it also picks up the new IP when the container is recreated, which the startup lookup never does.

On an older nginx the common trick is a variable, which forces a lookup per request through the resolver:

resolver 127.0.0.11 valid=30s;
set $up http://myapp:3000;
proxy_pass $up;

With a variable, a path inside it, as in http://myapp:3000/api/, replaces the whole request URI instead of only the matched part, so test a subpath. A resolver is also something you must trust: point it only at Docker’s DNS or your own, since nginx uses the answer for routing.

Further reading: ngx_http_upstream_module (server resolve), resolver

Going deeper: Guide: fix a 502 Bad Gateway in Nginx Proxy Manager, with a checklist that finds the cause

More Nginx tips sudo certbot --nginx -d example.com -d www.example.com /data/nginx/custom/server_redirect.conf map $http_upgrade $connection_upgrade { proxy_intercept_errors on; proxy_redirect http://localhost:3000/ /app/; All Nginx tips (50) All topics

Link