Nginx Reverse Proxy Builder · Docker Compose / Nginx

Nginx Reverse Proxy for Docker Compose Services (127.0.0.11 DNS Resolver)

Generate an Nginx reverse proxy server block for Docker Compose / Nginx with URL prefix rewrite previews, Certbot SSL redirects, WebSocket upgrade headers, and Docker DNS checks.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Domain, Routing & Upstream

2. TLS, WebSockets & Directives

# /etc/nginx/sites-available/api.dockerstack.dev.conf
# Generated by OpsCheck DevTools — Validate with: sudo nginx -t && sudo systemctl reload nginx

# Required in http {} context (or top of sites-available file) for clean WebSocket upgrades
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    listen [::]:80;
    server_name api.dockerstack.dev;

    # Redirect all plaintext HTTP traffic permanently to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name api.dockerstack.dev;

    # Let's Encrypt Certbot TLS Certificates
    ssl_certificate     /etc/letsencrypt/live/api.dockerstack.dev/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.dockerstack.dev/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    client_max_body_size 50M;

    # Gzip compression for JSON, JS, CSS, and SVG responses
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;

    # Baseline HTTP Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location /api/ {
        # Re-resolve Docker service IPs dynamically to avoid 502 after container restarts
        resolver 127.0.0.11 valid=30s ipv6=off;
        set $upstream_endpoint http://backend:8000;
        proxy_pass $upstream_endpoint;
        proxy_http_version 1.1;
        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;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;

        # WebSocket & Upgrade support (requires map $http_upgrade $connection_upgrade)
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_cache_bypass $http_upgrade;

        proxy_connect_timeout 15s;
        proxy_send_timeout 120s;
        proxy_read_timeout 120s;
    }
}
$sudo nginx -t && sudo systemctl reload nginx
URL Routing TransformationPrefix Preserved
GET https://api.dockerstack.dev/api/usershttp://backend:8000/api/users

Strip Prefix OFF: Nginx preserves the full URI so upstream receives '/api/users'.

Configuration Diagnostics

  • infoPrefix Preserved (/api/ Forwarded Intact)

    GET https://api.dockerstack.dev/api/users -> Upstream receives http://backend:8000/api/users. Strip Prefix OFF: Nginx preserves the full URI so upstream receives '/api/users'.

  • passWebSocket Upgrade & Extended Timeout (120s) Enabled

    Configured HTTP/1.1 Upgrade, Connection $connection_upgrade map, and extended proxy_read_timeout for persistent real-time sockets.

  • passDocker Embedded DNS Resolver (127.0.0.11) Active

    Using variable-based proxy_pass with resolver 127.0.0.11 valid=30s prevents stale container IP crashes when "backend" restarts or scales.

  • infoSingle-Layer CORS Policy Reminder

    This configuration intentionally omits Access-Control-Allow-Origin headers so your upstream backend framework (Laravel, FastAPI, Express, ASP.NET Core) owns CORS cleanly without duplicate header rejections.

Runs locally in your browser. Domain names and upstream topology are never sent to a server.

Common Nginx Error Log Pattern (Docker Compose / Nginx)

When upstream sockets, timeouts, body limits, or Docker DNS rules are misconfigured for Docker Compose / Nginx, Nginx typically records an entry matching the log line below inside /var/log/nginx/error.log:

/var/log/nginx/error.log

2026/11/22 19:02:15 [emerg] 1#1: host not found in upstream "backend:8000" in /etc/nginx/conf.d/default.conf:24

Reverse Proxy Architecture & Header Forwarding for Docker Compose / Nginx

Running Nginx as a container inside Docker Compose to reverse-proxy sibling services (such as http://backend:8000 or http://frontend:3000) introduces a notorious DNS caching failure that catches almost every DevOps team once. When you write a literal proxy_pass http://backend:8000; directive, Nginx resolves the hostname "backend" strictly ONCE at container startup using /etc/resolv.conf and caches the resulting IPv4 address indefinitely.

This creates two production outages. First, if the backend container is still booting or fails a healthcheck when Nginx starts, Nginx immediately exits with "[emerg] host not found in upstream" and enters a crash loop. Second, even if both containers start cleanly, running docker compose up -d --force-recreate backend assigns a brand-new bridge IP (for example, changing 172.18.0.4 to 172.18.0.9); yet Nginx keeps routing traffic to the dead 172.18.0.4 IP and serving 502 Bad Gateway until you manually restart Nginx.

The production fix is built directly into open-source Nginx: point resolver 127.0.0.11 valid=30s ipv6=off; at Docker's embedded DNS server and assign the upstream URL to an Nginx variable (set $upstream_endpoint http://backend:8000; proxy_pass $upstream_endpoint;). Whenever proxy_pass evaluates a variable, Nginx defers DNS resolution to request time and re-queries Docker's embedded DNS every 30 seconds.

Remember one crucial side effect of variable-based proxy_pass: Nginx no longer rewrites the URI automatically via a trailing slash. If you need to strip /api/ while using resolver 127.0.0.11, you must include an explicit rewrite ^/api/(.*)$ /$1 break; directive right before proxy_pass $upstream_endpoint; which the interactive builder above generates automatically.

When running Nginx as the edge ingress for a multi-container Docker Compose stack, mount your configuration files read-only (:ro), expose backend containers strictly on the private bridge network with expose instead of ports, and validate syntax via docker compose exec nginx nginx -t before sending SIGHUP (nginx -s reload). Pairing resolver 127.0.0.11 valid=30s ipv6=off with Docker healthchecks on every upstream container keeps deployments resilient even when individual microservices restart, scale horizontally, or receive new subnet IP addresses.

Step-by-Step Nginx & Docker Compose / Nginx Deployment Guide

Apply the Nginx server block above alongside these upstream framework trust-proxy settings so HTTPS detection, real client IPs, and reload safety work reliably in production.

  1. 1Place Nginx and Backend Services on a User-Defined Bridge Network

    docker-compose.yml

    Docker's embedded DNS server at 127.0.0.11 is ONLY active on user-defined bridge networks (never on the legacy default bridge). Declare an explicit internal network so Nginx resolves service names like "backend" reliably.

    docker-compose.ymlyaml
    services:
      nginx:
        image: nginx:1.27-alpine
        ports:
          - "80:80"
          - "443:443"
        volumes:
          - ./nginx/api.conf:/etc/nginx/conf.d/default.conf:ro
          - /etc/letsencrypt:/etc/letsencrypt:ro
        networks:
          - app_net
        restart: unless-stopped
    
      backend:
        build: ./backend
        expose:
          - "8000"
        networks:
          - app_net
        restart: unless-stopped
    
    networks:
      app_net:
        driver: bridge
  2. 2Use Docker Embedded Resolver 127.0.0.11 With Variable proxy_pass

    nginx/api.conf

    Declare resolver 127.0.0.11 valid=30s ipv6=off; and store the upstream target in set $upstream_endpoint. This prevents startup crash loops and eliminates stale-IP 502 errors after rolling backend restarts.

    nginx/api.confnginx
    location /api/ {
        resolver 127.0.0.11 valid=30s ipv6=off;
        set $upstream_endpoint http://backend:8000;
        proxy_pass $upstream_endpoint;
    
        proxy_http_version 1.1;
        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;
    }
  3. 3Add Explicit Rewrite Rules When Combining Docker Resolver With Strip Prefix

    nginx/api-strip.conf

    When proxy_pass uses a variable, trailing slashes do not strip location prefixes. Add rewrite ^/api/(.*)$ /$1 break; right before proxy_pass $upstream_endpoint; if your container expects /users instead of /api/users.

    nginx/api-strip.confnginx
    location /api/ {
        resolver 127.0.0.11 valid=30s ipv6=off;
        set $upstream_endpoint http://backend:8000;
        rewrite ^/api/(.*)$ /$1 break;
        proxy_pass $upstream_endpoint;
    }
  4. 4Test Zero-Downtime Backend Recreation Without Restarting Nginx

    terminal

    Verify that Nginx stays healthy and cleanly resolves the new IP after recreating the backend container.

    terminalbash
    docker compose exec nginx nginx -t
    docker compose up -d --force-recreate backend
    # Within 30s (or immediately on cache expiry), requests succeed with zero Nginx reload:
    curl -I https://api.dockerstack.dev/api/health

Common Docker Compose / Nginx Nginx Reverse Proxy Pitfalls

Review these three production failure modes before reloading Nginx on staging or live servers.

Pitfall 1

Using resolver 127.0.0.11 Without a Variable in proxy_pass

Adding resolver 127.0.0.11 valid=30s; while keeping a static literal proxy_pass http://backend:8000; does NOTHING in open-source Nginx; Nginx only invokes the runtime resolver when proxy_pass contains at least one variable like $upstream_endpoint.

Pitfall 2

Forgetting ipv6=off Inside IPv4-Only Docker Bridge Networks

By default, Nginx queries both A (IPv4) and AAAA (IPv6) records from 127.0.0.11. On IPv4-only Docker bridges, AAAA lookups can introduce latency or log spurious resolver errors. Always append ipv6=off unless IPv6 Docker networking is explicitly configured.

Pitfall 3

Publishing Backend Ports With "ports:" Instead of "expose:"

Using ports: ["8000:8000"] binds the backend to 0.0.0.0:8000 on the host firewall (bypassing UFW on Docker hosts!). Use expose: ["8000"] so only containers on app_net, like Nginx, can reach your backend API.

Related Tools

Pair this Nginx reverse proxy block with healthcheck-gated Docker Compose orchestration and verified browser CORS headers:

Frequently Asked Questions

Why does Docker use 127.0.0.11 as the DNS resolver IP?
Docker Engine embeds an internal DNS server listening on loopback address 127.0.0.11 inside every container attached to a user-defined network. It resolves container service names dynamically and forwards external DNS lookups to the host resolvers.
What happens if I scale my Docker backend to 3 replicas with resolver 127.0.0.11?
Docker's embedded DNS returns all healthy replica IPs in round-robin order for the service name "backend". With valid=10s or valid=30s, Nginx distributes requests across replicas automatically as containers scale up or down.
Why did my query strings disappear after using variable proxy_pass?
If you write proxy_pass $upstream_endpoint/; with a trailing slash or URI part alongside a variable, Nginx replaces the entire request URI. Pass bare proxy_pass $upstream_endpoint; (with no trailing URI) so Nginx forwards $request_uri including query parameters intact.
Can I use upstream {} blocks together with resolver 127.0.0.11 in open-source Nginx?
Dynamic re-resolution inside upstream {} blocks (server backend:8000 resolve;) was historically an Nginx Plus feature (added to open-source Nginx only in 1.27.3+). The set $upstream_endpoint + resolver 127.0.0.11 pattern works reliably across every Nginx version.
Browse all 10 Nginx guides →