Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 111 ยท Language Recipes

Nginx and Reverse Proxies

Run nginx in Docker as a static file server and reverse proxy: config mounts, templates, proxy_pass pitfalls, TLS termination, health checks, plus Caddy and Traefik.

Almost every container that serves web traffic ends up behind another web server. That server, usually nginx, Caddy or Traefik, sits at the front door: it serves static files, forwards other requests to your application containers, terminates HTTPS and hides how many services are behind it. This pattern is called a reverse proxy, and knowing it well is the difference between a demo and a deployment.

In this lesson you will run nginx as a static file server, mount and reload its configuration, put it in front of a backend service in Compose, learn the proxy_pass details that cause most outages, terminate TLS, and then see the same job done with Caddy. Traefik gets an honest overview, as a read-only example. All the nginx and Caddy commands below ran on nginx 1.31 and Caddy 2.11. Compose is used throughout; refresh with Introduction to Docker Compose if you need to.

What a reverse proxy does

TEXT
                       +-------------------------------+
  browser ---HTTPS---> |  proxy (nginx / Caddy)        |
                       |  - TLS certificates           |
                       |  - static files               |
                       |  - routing by path or host    |
                       +---------+---------------+-----+
                                 |  plain HTTP   |   on a private Docker network
                          /api/* |               | everything else
                                 v               v
                           [ api container ]  [ files on disk ]

Only the proxy publishes a port. The application containers have no published ports at all; they are reachable only through the Docker network, by service name (see Containers Talking to Each Other). That gives you one place to apply TLS, compression, caching, rate limits and access logs.

nginx as a static server

The official nginx:alpine image serves /usr/share/nginx/html on port 80. The smallest useful experiment mounts your folder over it:

CONSOLE
$ mkdir site && echo '<h1>Served by nginx</h1>' > site/index.html
$ docker run -d --name web -p 127.0.0.1:8080:80 \
    -v "$PWD/site:/usr/share/nginx/html:ro" nginx:alpine
$ curl -s 127.0.0.1:8080/
<h1>Served by nginx</h1>

The :ro flag mounts the folder read-only, since nginx never needs to write there. Edit the file on your host and refresh: a bind mount shows changes at once (see Bind Mounts). That is perfect for development. For production, bake the files into an image so a deploy is a single, versioned artifact:

DOCKERFILE
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY site /usr/share/nginx/html
HEALTHCHECK --interval=5s --timeout=3s CMD wget -qO- http://127.0.0.1/healthz || exit 1

The healthcheck uses wget, which the Alpine-based image includes (the image has no curl). Our configuration below defines the /healthz location. We built and ran this image and it reported Up 9 seconds (healthy); the final image was 93.6 MB, about the same as the base. Look at what runs inside:

CONSOLE
$ docker exec web ps
PID   USER     TIME  COMMAND
    1 root      0:00 nginx: master process nginx -g daemon off;
   28 nginx     0:00 nginx: worker process
   29 nginx     0:00 nginx: worker process

The master process runs as root (it needs to bind port 80 and read certificates), while the workers that handle requests run as the unprivileged nginx user. If your policy forbids root entirely, use the nginxinc/nginx-unprivileged image, which listens on port 8080 instead (read-only suggestion, not run here). More on users in Users and Permissions.

The configuration lives in conf.d

The default image includes /etc/nginx/nginx.conf, which pulls in every file in /etc/nginx/conf.d/. You normally replace only conf.d/default.conf and leave the main file alone. Here is a complete server block for a static site that also forwards /api/ to a backend:

NGINX
server {
    listen 80;
    server_name _;

    root /usr/share/nginx/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    location /api/ {
        proxy_pass http://api:80/;
        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;
    }

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

And a Compose file with two services. To keep the example self-contained, the "API" is a second nginx whose config answers with a JSON description of the request it received. A real backend would be your Node, Python or Go container:

YAML
services:
  proxy:
    image: nginx:alpine
    ports:
      - "127.0.0.1:8080:80"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - ./site:/usr/share/nginx/html:ro
    depends_on:
      - api

  api:
    image: nginx:alpine
    volumes:
      - ./api/default.conf:/etc/nginx/conf.d/default.conf:ro
CONSOLE
$ docker compose up -d
$ curl -s 127.0.0.1:8080/
<!doctype html>
<html lang="en">
  <head><meta charset="utf-8"><title>Static site</title></head>
  <body><h1>Served by nginx</h1></body>
</html>
$ curl -s 127.0.0.1:8080/healthz
ok
$ curl -s -i 127.0.0.1:8080/missing | head -1
HTTP/1.1 404 Not Found
$ curl -s "127.0.0.1:8080/api/users?id=7"
{"service":"api","host":"127.0.0.1","real_ip":"172.21.0.1","forwarded_for":"172.21.0.1","proto":"http","uri":"/users?id=7"}

The last line is the backend's own report of what it received. It saw /users?id=7, the path without the /api prefix, the original Host, and the client address (172.21.0.1 is the Docker network gateway, which is how a client on the host appears; in production it would be the visitor's address) in X-Real-IP and X-Forwarded-For. Those headers are not decoration. Without them the backend would see every request coming from the proxy's address, and could not tell http from https.

Edit, test, reload

Never restart a proxy to change config. Test the new file inside the running container, then ask nginx to reload gracefully:

CONSOLE
$ docker compose exec proxy nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
$ docker compose exec proxy nginx -s reload

A reload starts new worker processes with the new configuration and lets old workers finish their current requests, so no connection is dropped. If the file is broken, nginx -t tells you where, and the old configuration keeps serving:

CONSOLE
$ docker compose exec proxy nginx -t
2026/10/23 16:23:07 [emerg] 58#58: unknown directive "bogus" in /etc/nginx/conf.d/default.conf:26
nginx: [emerg] unknown directive "bogus" in /etc/nginx/conf.d/default.conf:26
nginx: configuration file /etc/nginx/nginx.conf test failed

If the bind-mounted config is a single file, some editors replace the file with a new one (new inode) and the container keeps seeing the old content. Mount the directory that holds the config when you edit often, or restart the container after the change.

proxy_pass pitfalls that cause real outages

The trailing slash

Whether proxy_pass ends in / changes the path the backend receives. We changed one character and repeated the same request:

CONSOLE
$ # proxy_pass http://api:80/;   (with trailing slash)
$ curl -s "127.0.0.1:8080/api/users?id=7"
{"service":"api",...,"uri":"/users?id=7"}

$ # proxy_pass http://api:80;    (no slash)
$ curl -s "127.0.0.1:8080/api/users?id=7"
{"service":"api",...,"uri":"/api/users?id=7"}

With a trailing slash (a URI part), nginx replaces the matched location prefix (/api/) with that URI. Without it, the full original path is passed on. Neither is wrong; the bug is not knowing which one your backend expects.

Names are resolved once

nginx resolves a hostname in proxy_pass when it loads the configuration and remembers the address. Two consequences, both of which we reproduced:

  1. If the backend does not exist yet when nginx starts, nginx refuses to start:
CONSOLE
$ docker compose up -d proxy --no-deps
$ docker compose logs proxy | grep emerg
proxy-1  | 2026/10/23 16:26:05 [emerg] 1#1: host not found in upstream "api" in /etc/nginx/conf.d/default.conf:13
$ docker compose ps -a --format '{{.Service}} {{.Status}}'
proxy Exited (1) 21 seconds ago
  1. If the backend container is replaced and gets a new IP, nginx keeps sending traffic to the old address. We stopped the api container: requests hung until nginx gave up, and the client got 504:
CONSOLE
$ docker compose stop api
$ curl -s -o /dev/null -w '%{http_code}\n' 127.0.0.1:8080/api/x
504
$ docker compose logs proxy | grep error | tail -1
proxy-1  | 2026/10/23 16:24:09 [error] 53#53: *10 upstream timed out (110: Operation timed out) while connecting to upstream, client: 172.21.0.1, server: _, request: "GET /api/x HTTP/1.1", upstream: "http://172.21.0.2:80

(The request took about a minute: that is nginx's connect timeout.) The remedy is to tell nginx to resolve at request time. Use Docker's embedded DNS server at 127.0.0.11 and put the target in a variable, since nginx only re-resolves when the address is a variable:

NGINX
server {
    listen 80;
    resolver 127.0.0.11 valid=10s;

    location /api/ {
        set $backend http://api:80;
        rewrite ^/api/(.*)$ /$1 break;
        proxy_pass $backend;
    }
}

With this config nginx starts even when api does not exist, and answers 502 Bad Gateway instead of crashing:

CONSOLE
$ curl -s -o /dev/null -w '%{http_code}\n' 127.0.0.1:8080/api/x
502

Note the explicit rewrite: when proxy_pass uses a variable, nginx does not strip the prefix by itself, so you strip it yourself. For simple stacks, ordering with healthchecks (see Startup Order and Health) and restarting the proxy after a backend is replaced works too, but the resolver approach is the robust one.

Configuration from environment variables

The nginx config language has no environment variables. The official image works around that: any file in /etc/nginx/templates/ ending in .template is run through envsubst at start-up and written to conf.d/ without the suffix. Given default.conf.template:

NGINX
server {
    listen ${PORT};
    location / {
        return 200 "backend is ${BACKEND_HOST}\n";
    }
}
CONSOLE
$ docker run -d --name tpl -e PORT=8081 -e BACKEND_HOST=api.internal \
    -v "$PWD/tpl:/etc/nginx/templates:ro" -p 127.0.0.1:8081:8081 nginx:alpine
$ docker logs tpl 2>&1 | grep envsubst
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
20-envsubst-on-templates.sh: Running envsubst on /etc/nginx/templates/default.conf.template to /etc/nginx/conf.d/default.conf
$ curl -s 127.0.0.1:8081/
backend is api.internal

Only variables that exist in the environment are substituted, so nginx's own $host or $uri stay untouched (they have no braces and are not in the environment). This is how one image serves staging and production with different upstream names.

TLS termination

Terminating TLS in the proxy means your backends only speak plain HTTP on the private network, and only one component deals with certificates. For local experiments create a self-signed certificate; in production you would use a certificate from Let's Encrypt or your provider. We generated one in a throwaway Alpine container:

CONSOLE
$ mkdir certs
$ docker run --rm -v "$PWD/certs:/certs" alpine:3 sh -c 'apk add -q --no-cache openssl && \
    openssl req -x509 -newkey rsa:2048 -nodes -days 30 -subj "/CN=localhost" \
    -addext "subjectAltName=DNS:localhost" -keyout /certs/localhost.key -out /certs/localhost.crt'
$ ls certs
localhost.crt  localhost.key

The nginx side has two server blocks: port 80 redirects to HTTPS, port 443 holds the certificate and forwards to the backend with the right X-Forwarded-Proto:

NGINX
server {
    listen 80;
    server_name localhost;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    http2 on;
    server_name localhost;

    ssl_certificate     /etc/nginx/certs/localhost.crt;
    ssl_certificate_key /etc/nginx/certs/localhost.key;
    ssl_protocols       TLSv1.2 TLSv1.3;

    location / {
        proxy_pass http://api:80;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

In Compose, publish both ports and mount the certificates read-only:

YAML
services:
  proxy:
    image: nginx:alpine
    ports:
      - "127.0.0.1:8080:80"
      - "127.0.0.1:8443:443"
    volumes:
      - ./nginx-tls.conf:/etc/nginx/conf.d/default.conf:ro
      - ./certs:/etc/nginx/certs:ro
    depends_on:
      - api
CONSOLE
$ curl -si http://127.0.0.1:8080/hello | grep -iE "^HTTP|^location"
HTTP/1.1 301 Moved Permanently
Location: https://127.0.0.1/hello
$ curl -k https://localhost:8443/hello
{"service":"api","host":"localhost","real_ip":"","forwarded_for":"172.21.0.1","proto":"https","uri":"/hello"}
$ curl https://localhost:8443/hello
curl: (60) the certificate is not trusted (message wording depends on your curl build)

Three observations. The backend now sees "proto":"https", which is how frameworks know to generate https:// links. Plain curl rejects the self-signed certificate and -k skips the check; never do that against real sites. And the redirect target is https://127.0.0.1/hello without our unusual port 8443, because $host carries no port. On standard ports 80 and 443, which is what production uses, this is exactly right; in a local test with odd ports, use $host:8443 or just test the HTTPS URL directly.

Never bake private keys into an image. Mount them (as here), or use secrets (see Managing Secrets). Certificate renewal is the big operational burden of this setup, which is why Caddy and Traefik exist.

Caddy: automatic HTTPS and a shorter config

Caddy is a Go web server whose headline feature is that it obtains and renews Let's Encrypt certificates for you. Its configuration file, the Caddyfile, is very short. The same routing as above (static files plus /api/* forwarded with the prefix removed):

TEXT
:80 {
	handle_path /api/* {
		reverse_proxy api:80
	}
	handle {
		root * /srv
		file_server
	}
}
YAML
services:
  caddy:
    image: caddy:alpine
    ports:
      - "127.0.0.1:8080:80"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - ./site:/srv:ro
      - caddy_data:/data
    depends_on:
      - api
  api:
    image: nginx:alpine
    volumes:
      - ./api/default.conf:/etc/nginx/conf.d/default.conf:ro
volumes:
  caddy_data:
CONSOLE
$ docker compose exec caddy caddy version
v2.11.7 h1:yj0Y4fYZGPkSvibBJ1sTWE33xC0fxztVyXEW5iIdUT4=
$ curl -s 127.0.0.1:8080/api/users?id=7
{"service":"api","host":"127.0.0.1","real_ip":"","forwarded_for":"172.21.0.1","proto":"http","uri":"/users?id=7"}

handle_path strips the prefix (like our trailing slash); reverse_proxy sets the forwarding headers by itself and re-resolves names for you, so the two nginx pitfalls above do not apply. The caddy_data volume stores certificates and keys, so persist it, or Caddy asks for new certificates on every restart and may hit rate limits.

With a real domain name instead of :80, HTTPS becomes automatic (read-only example, it needs public DNS and ports 80 and 443 reachable from the internet):

TEXT
app.example.com {
	reverse_proxy app:3000
}

Caddy then obtains a certificate for app.example.com, serves HTTPS, redirects HTTP to HTTPS and renews before expiry. That is three lines for what takes dozens in nginx plus a certbot cron job.

Traefik: routing from container labels

Traefik takes a different approach: instead of a config file you edit, it watches Docker and builds routes from labels on your containers. Add a container, give it labels, and Traefik routes to it without a reload. A typical example looks like this (read-only; not run here because Traefik needs access to the Docker socket, which is a significant security risk: see Securing the Docker Daemon):

YAML
services:
  traefik:
    image: traefik:v3
    command:
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

  api:
    image: my-api:1.0
    labels:
      - traefik.enable=true
      - traefik.http.routers.api.rule=Host(`api.example.com`)
      - traefik.http.services.api.loadbalancer.server.port=3000

Traefik shines when you have many services that come and go (it is the default ingress in some Kubernetes and Swarm setups). The price is a steeper learning curve and the socket access. A mitigation is a socket proxy that exposes only read-only API calls. For a handful of fixed services on one host, nginx or Caddy is simpler.

Which one should you pick?

Need Good choice
Static files and a few upstreams, full control, widest documentation nginx
Automatic HTTPS with minimal config Caddy
Many dynamic services, routes defined next to the container Traefik
Already on Kubernetes The cluster's ingress controller

Whichever you choose, the habits are the same: publish only the proxy, bind it deliberately, keep backends on a private network, send real client information in headers, test the configuration before reloading, and keep certificates out of images.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a Compose stack with a reverse proxy, which container should publish ports to the host?

    The proxy is the single entry point. Backends have no published ports and are reachable only over the Docker network by service name, which reduces the attack surface.
  2. 2. A location has proxy_pass http://api:80/; (with trailing slash) and matches /api/users. What path does the backend receive?

    When proxy_pass has a URI part (even just a slash), nginx replaces the matched prefix with it. Our test showed uri /users?id=7; without the slash the backend saw /api/users?id=7.
  3. 3. Why does nginx exit with host not found in upstream when started before its backend container?

    Static host names in proxy_pass are resolved at start-up. Use resolver 127.0.0.11 with a variable in proxy_pass to resolve at request time, and nginx will start and return 502 until the backend exists.
  4. 4. What is the safest way to change an nginx configuration in a running container?

    nginx -t validates the new file and a graceful reload swaps workers without dropping connections. If the test fails, the old configuration keeps running.
  5. 5. What advantage does Caddy have over a plain nginx setup for public websites?

    With a real domain name in the Caddyfile, Caddy gets a Let's Encrypt certificate, redirects HTTP to HTTPS and renews it. Persist its /data volume so certificates survive restarts.

Summary

  • A reverse proxy is the single public entry point: it serves static files, routes to backends by path or host, terminates TLS and adds forwarding headers. Publish only its ports.
  • nginx reads /etc/nginx/conf.d/*.conf. Mount your file read-only, validate with nginx -t, apply with nginx -s reload. Bake files into an image for production.
  • A trailing slash on proxy_pass strips the location prefix; no slash passes the full path. Always set Host, X-Real-IP, X-Forwarded-For and X-Forwarded-Proto.
  • nginx resolves upstream names once. Use resolver 127.0.0.11 plus a variable (and an explicit rewrite) so it survives backend restarts and missing backends.
  • Use /etc/nginx/templates/*.template to inject environment variables into configs. Keep certificates and keys out of images.
  • Caddy gives automatic HTTPS and short configs; Traefik builds routes from container labels but needs Docker socket access.

Next: Why Orchestration?