fix: nginx 502 after API container restart (dynamic DNS resolver)

Without a resolver directive, nginx resolves upstream hostnames once at
startup and caches the IP forever. When the API container restarts it gets
a new Docker-assigned IP, causing 502 Bad Gateway until nginx is reloaded.

Fix:
- Add 'resolver 127.0.0.11 valid=10s' (Docker embedded DNS)
- Use a variable in proxy_pass ('set \ api') so nginx
  re-resolves on every request using the resolver above
- Variable proxy_pass passes the full request URI as-is, so /api/...
  correctly maps to http://api:8000/api/... without double-pathing
This commit is contained in:
Cog
2026-03-11 22:28:39 -05:00
committed by Jason Staack
parent 58597ad4fd
commit 21b8ce029f

View File

@@ -2,6 +2,10 @@ server {
listen 80; listen 80;
server_name _; server_name _;
# Use Docker's embedded DNS resolver so nginx re-resolves upstream hostnames
# dynamically instead of caching IPs at startup (prevents 502 after container restarts).
resolver 127.0.0.11 valid=10s ipv6=off;
root /usr/share/nginx/html; root /usr/share/nginx/html;
index index.html; index index.html;
@@ -19,7 +23,11 @@ server {
# Proxy API requests to the backend service # Proxy API requests to the backend service
# The api container is reachable via Docker internal DNS as "api" on port 8000 # The api container is reachable via Docker internal DNS as "api" on port 8000
location /api/ { location /api/ {
proxy_pass http://api:8000/api/; # Use a variable so nginx applies the resolver on every request.
# With a variable in proxy_pass, nginx passes the full request URI as-is
# (no path stripping), so the upstream receives /api/... correctly.
set $api_upstream api;
proxy_pass http://$api_upstream:8000;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;