basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ConfigHomelabnginx

    nginx in Docker and in front of containers: unprivileged, templates, and DNS resolver

    Two container setups line by line: a hardened unprivileged static container (nginx-unprivileged, read_only, /healthz, built-in envsubst from /etc/nginx/templates/) and an nginx reverse proxy in front of Docker Compose services with dynamic DNS via resolver 127.0.0.11.

    Scenario 1: static site container (nginx-unprivileged and templates/)

    When you pack a frontend (Astro, React, Hugo) into its own container behind Traefik or another proxy, nginx inside needs five things: non-root execution, a read-only filesystem (read_only), a /healthz endpoint that stays out of logs, logs to stdout/stderr, and environment variable substitution on startup.

    The official nginx image (and nginxinc/nginx-unprivileged) handles variable substitution out of the box: on startup, /docker-entrypoint.d/20-envsubst-on-templates.sh reads every *.template file in /etc/nginx/templates/, substitutes defined environment variables, and writes the rendered *.conf files to /etc/nginx/conf.d/.

    /etc/nginx/templates/default.conf.template
    server {
        listen ${NGINX_PORT};
        server_name _;
        server_tokens off;
        root /usr/share/nginx/html;
        absolute_redirect off;
    Key part

    The port comes from NGINX_PORT (8080 for the unprivileged image). server_tokens off hides the nginx version, and absolute_redirect off keeps the internal port 8080 out of redirects like /docs to /docs/.

        location = /healthz {
            access_log off;
            default_type text/plain;
            return 200 "ok\n";
        }
    Key part

    Health endpoint for Docker HEALTHCHECK: skips access.log, avoids disk I/O, and returns 200 ok immediately.

        location ^~ /assets/ {
            add_header Cache-Control "public, max-age=31536000, immutable" always;
            try_files $uri =404;
        }
    
        location / {
            add_header Cache-Control "no-cache" always;
            try_files $uri $uri/ =404;
        }
    }

    Static files and hashed assets (full breakdown in Static & SPA). The entrypoint script leaves $uri untouched as long as no uri variable exists in the container environment.

    A working docker-compose.yaml with container hardening (Hardening containers in Compose):

    services:
      web:
        image: nginxinc/nginx-unprivileged:1.30-alpine
        restart: unless-stopped
        read_only: true
        cap_drop: [ALL]
        security_opt:
          - no-new-privileges:true
        environment:
          NGINX_PORT: "8080"
        volumes:
          - ./templates:/etc/nginx/templates:ro
          - ./dist:/usr/share/nginx/html:ro
        tmpfs:
          - /tmp:noexec,nosuid
          - /var/cache/nginx:noexec,nosuid
          - /etc/nginx/conf.d:noexec,nosuid
        healthcheck:
          test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
          interval: 30s
          timeout: 3s
          retries: 3

    Standard nginx:alpine images already symlink /var/log/nginx/access.log and error.log to /dev/stdout and /dev/stderr, so docker logs captures every request with no extra config.

    Scenario 2: nginx reverse proxy in front of Docker Compose services

    When nginx proxies traffic to several containers on a user-defined Docker network (docker network create proxy, Docker networks), the main trap is DNS caching.

    If you write proxy_pass http://api:8000; directly, nginx resolves api once at startup. Two things break:

    1. If the api container is stopped, nginx refuses to start (host not found in upstream).
    2. If you recreate api during a deploy and Docker assigns a new IP, nginx keeps hitting the stale IP and returning 502/504.

    To fix both, point nginx at Docker’s embedded DNS (127.0.0.11) and pass the upstream URL to proxy_pass via a set variable. nginx then resolves the hostname at request time and refreshes it every valid=30s.

    /etc/nginx/templates/proxy.conf.template
    server {
        listen 8080;
        server_name app.example.org;
        resolver 127.0.0.11 valid=30s ipv6=off;
    Key part

    Docker’s embedded DNS server for user-defined networks always runs at 127.0.0.11. valid=30s sets the IP cache TTL, and ipv6=off skips unnecessary AAAA lookups on an IPv4 container network.

        location /api/ {
            include snippets/proxy-headers.conf;
            proxy_set_header Connection "";
            set $api_upstream http://${API_HOST}:8000;
            proxy_pass $api_upstream;
        }
    Key part

    Using $api_upstream forces nginx to query resolver on incoming requests instead of at startup. If api is down, nginx still starts cleanly and returns 502 on /api/ until the backend comes up.

        location /v1/ {
            include snippets/proxy-headers.conf;
            proxy_set_header Connection "";
            set $v1_upstream http://${API_HOST}:8000;
            rewrite ^/v1/(.*)$ /$1 break;
            proxy_pass $v1_upstream;
        }
    }

    When proxy_pass uses a variable, a trailing slash will not strip the /v1/ prefix — rewrite the URI explicitly with rewrite … break.

    How to check

    1. Start a test container using the template with an intentionally missing API_HOST=missing-backend:
      docker run -d --name test-ngx --network proxy -p 127.0.0.1:8180:8080 \
        -e NGINX_PORT=8080 -e API_HOST=missing-backend \
        -v ./templates:/etc/nginx/templates:ro \
        -v ./dist:/usr/share/nginx/html:ro \
        nginxinc/nginx-unprivileged:1.30-alpine
    2. Verify that envsubst rendered the config and the container stayed up:
      docker exec test-ngx grep -E 'listen|set \$api_upstream' /etc/nginx/conf.d/default.conf
      #     listen 8080;
      #         set $api_upstream http://missing-backend:8000;
    3. Check /healthz, static files, and that the missing backend returns 502 instead of crashing nginx:
      curl -s http://127.0.0.1:8180/healthz
      # ok
      curl -s -o /dev/null -w "api:%{http_code}\n" http://127.0.0.1:8180/api/ping
      # api:502

    If it doesn’t work

    The nginx proxy container exits immediately on startup with host not found in upstream "api"

    Cause
    proxy_pass http://api:8000; hardcodes the hostname, so nginx resolves it once at startup. If the api container isn’t running yet, nginx refuses to start.
    Fix
    Add Docker’s embedded DNS resolver 127.0.0.11 valid=30s ipv6=off; and pass the upstream through a variable: set $api http://api:8000; proxy_pass $api;.

    After docker compose up -d --force-recreate api, the nginx proxy returns 502 or 504 even though the new api container is healthy

    Cause
    The recreated container got a new IP on the Docker network, while nginx without a resolver and variable kept the old IP cached from startup.
    Fix
    Switch proxy_pass to resolver 127.0.0.11 valid=30s plus a set $api … variable so nginx picks up the new IP within 30 seconds without a restart.

    nginxinc/nginx-unprivileged fails to start with bind() to 0.0.0.0:80 failed (13: Permission denied)

    Cause
    The unprivileged container user (uid 101) cannot bind ports below 1024.
    Fix
    Listen on port 8080 inside the container (listen 8080;) and map host or reverse-proxy traffic to 8080.

    With read_only: true, nginx fails on startup: mkdir() "/var/cache/nginx/client_temp" failed (30: Read-only file system)

    Cause
    nginx needs writable directories for temporary buffers, its PID file, and configs rendered from /etc/nginx/templates/.
    Fix
    Mount tmpfs on /tmp, /var/cache/nginx, and /etc/nginx/conf.d (when using templates/).

    The /etc/nginx/templates/default.conf.template file wipes out $host and $uri, leaving them blank in the rendered config

    Cause
    Either envsubst was run manually without a variable allowlist, or the container environment defines a HOST or URI variable.
    Fix
    The image’s built-in script (20-envsubst-on-templates.sh) substitutes only variables that exist in the container environment. Prefix custom variables (NGINX_PORT, API_HOST) so they never collide with nginx variables.