Skip to content
ES EN
Theme: automatic

Lab · Defensive security

Build a hardened NGINX reverse proxy with TLS and rate limits in Docker

Deploy NGINX 1.30.8 as a reverse proxy in Docker Compose with TLS, security headers, request rate limiting, rotated logs and a full cleanup at the end.

Lab · Defensive security

40 min intermediate level validated configuration

Lab architectureComponents: Browser, NGINX 1.30.8, whoami backend, TLS certificate, Log rotation.HTTPS / HTTPinternal HTTPmounted (read-only)reads ./logs and sign…Browser: step 1BrowserHTTPS clientTLS certificate: step 1TLS certificateOpenSSL, ./certsLog rotation: step 4Log rotationCompose containerNGINX 1.30.8: step 3NGINX 1.30.8reverse proxy :8443 and…whoami backend: step 3whoami backendinternal network :80
  1. Browser · step 1 HTTPS client
  2. NGINX 1.30.8 · step 3 reverse proxy :8443 and :8080
  3. whoami backend · step 3 internal network :80
  4. TLS certificate · step 1 OpenSSL, ./certs
  5. Log rotation · step 4 Compose container

What you will build and why

In this lab you will set up an NGINX reverse proxy as the single entry point to an internal service on your home server. NGINX terminates TLS with a certificate generated by OpenSSL, adds security headers, limits the request rate per IP and writes logs that a second container rotates periodically.

We pin the version to the stable branch shown on the nginx download page: 1.30.8. According to the release notes, 1.30.7 fixes several vulnerabilities (resolver, HTTP/2, HTTP/3, body reading over TLS 1.3, alias with try_files, among others) and 1.30.8 fixes excessive CPU usage with ssl_early_data. It is worth not staying on an old version while also avoiding floating tags that change without warning.

The sample backend is a traefik/whoami container pinned to v1.12.0, with no published ports: it is reachable only through the proxy. Replace it with your real application when you are done. Everything marked CHANGE_ME_… must be replaced with your own value. The commands use brace expansion, so you need bash or zsh.

Lab: Build a hardened NGINX reverse proxy with TLS and rate limits in Docker

Requirements

SystemLinux (Debian 12 / Ubuntu 24.04) or macOS 14
NGINX (imagen nginx)1.30.8
Docker Compose v2 (Compose Specification, versión mínima)1.27.0
traefik/whoami (imagen del backend)v1.12.0
Alpine (imagen del contenedor de rotación)3.24.4
RAM1 GB
Disk2 GB

Step by step

  1. Prepare the directory and generate the TLS certificate

    We create the project structure and a self-signed certificate for local testing. For a public domain use a real certificate from your CA; the NGINX mount is identical, because ssl_certificate and ssl_certificate_key expect PEM files.

    Replace CHANGE_ME_DOMAIN with the name you will use to reach the proxy (for example proxy.lan) in this command and, later, in conf/nginx.conf. The private key gets restrictive permissions. The brace expansion in mkdir requires bash or zsh.

    mkdir -p nginx-hardened/{certs,conf,logs}
    cd nginx-hardened
    openssl req -x509 -newkey rsa:4096 -nodes -sha256 -days 365 -keyout certs/server.key -out certs/server.crt -subj "/CN=CHANGE_ME_DOMAIN"
    chmod 600 certs/server.key
    chmod 644 certs/server.crt
  2. Write the hardened NGINX configuration

    This nginx.conf is complete. It defines a per-IP request limit zone with limit_req_zone (we use $binary_remote_addr, which is more compact than $remote_addr), restricts protocols to TLS 1.2 and 1.3 with ssl_protocols, adds security headers with always so they are also sent on error responses, and forwards requests to the internal backend with proxy_pass. Before saving, replace CHANGE_ME_DOMAIN with your domain; since it is the only server listening on 443, it serves any TLS request even if the name does not match.

    One important detail: add_header is inherited from the previous level only if the current level defines none. That is why we put all the headers in the same server block. The HSTS value is short (300 s) so that, in a lab with a self-signed certificate, the browser does not stay pinned to HTTPS for months; raise it once you use a real certificate.

    The internal port 80 block redirects to HTTPS; in Compose we will publish it on 127.0.0.1:8080, so you can check the redirect. Logs go to files under /var/log/nginx, which we will mount at ./logs.

    File conf/nginx.conf

    worker_processes auto;
    
    events {
        worker_connections 1024;
    }
    
    http {
        server_tokens off;
    
        log_format main '$remote_addr [$time_local] "$request" $status $body_bytes_sent "$http_user_agent" rl=$limit_req_status';
        access_log /var/log/nginx/access.log main;
        error_log /var/log/nginx/error.log warn;
    
        limit_req_zone $binary_remote_addr zone=perip:10m rate=5r/s;
        limit_req_status 429;
        limit_req_log_level warn;
    
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
    
        server {
            listen 80;
            return 301 https://$host:8443$request_uri;
        }
    
        server {
            listen 443 ssl;
            server_name CHANGE_ME_DOMAIN;
    
            ssl_certificate /etc/nginx/certs/server.crt;
            ssl_certificate_key /etc/nginx/certs/server.key;
    
            add_header Strict-Transport-Security "max-age=300" always;
            add_header X-Content-Type-Options "nosniff" always;
            add_header X-Frame-Options "DENY" always;
            add_header Referrer-Policy "no-referrer" always;
            add_header Content-Security-Policy "default-src 'self'" always;
    
            location / {
                limit_req zone=perip burst=10 nodelay;
                proxy_pass http://backend:80;
                proxy_http_version 1.1;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_read_timeout 30s;
            }
        }
    }

    Replace every CHANGE_ME_… value with your own before starting: never keep example passwords or keys.

  3. Define the Compose file with pinned versions and start it

    The main service is NGINX with the exact tag 1.30.8. The backend (traefik/whoami:v1.12.0) publishes no port: it lives only on the internal Compose network, so the only path to it goes through the proxy and its limits.

    We publish the proxy only on 127.0.0.1: 8443 for HTTPS and 8080 for the redirect from HTTP. If you want to expose it to your local network, change those addresses deliberately. We mount the configuration and certificates read-only (:ro) and the logs read-write.

    File compose.yaml

    services:
      nginx:
        image: nginx:1.30.8
        ports:
          - "127.0.0.1:8443:443"
          - "127.0.0.1:8080:80"
        volumes:
          - ./conf/nginx.conf:/etc/nginx/nginx.conf:ro
          - ./certs:/etc/nginx/certs:ro
          - ./logs:/var/log/nginx
        depends_on:
          - backend
        restart: unless-stopped
    
      backend:
        image: traefik/whoami:v1.12.0
        restart: unless-stopped
    docker compose config --quiet
    docker compose up -d
    docker compose ps

    Expected output (illustrative: the exact format may vary)

    NAME                       IMAGE                      COMMAND                  SERVICE   STATUS         PORTS
    nginx-hardened-backend-1   traefik/whoami:v1.12.0     "/whoami"                backend   Up 5 seconds   80/tcp
    nginx-hardened-nginx-1     nginx:1.30.8               "/docker-entrypoint.…"   nginx     Up 4 seconds   127.0.0.1:8080->80/tcp, 127.0.0.1:8443->443/tcp
  4. Add log rotation as a Compose service

    Access logs grow without limit if nobody rotates them. We add a second service, an alpine container with a simple loop that checks every hour whether access.log or error.log exceeds 10 MB. If so, it renames them (keeping five copies) and sends the USR1 signal to the NGINX master process so it reopens the files.

    To signal NGINX without mounting the Docker socket (which would give this container almost total control of the host), the rotation container shares the process namespace of the NGINX container with pid: "container:nginx-hardened-proxy", using the fixed name we give NGINX with container_name. If you change that name, change it in both places.

    The script installs nothing: it finds the master process by reading its command line in /proc with BusyBox utilities and sends it kill -USR1. It rotates only when it finds the PID, because renaming the files without telling NGINX would be pointless. The logrotate service depends on nginx with condition: service_started so the NGINX container exists at startup.

    Replace the file with this complete version. Because container_name is added, Compose recreates the NGINX container. The 10 MB threshold will not be reached during the lab; if you want to see a rotation, temporarily lower 10485760 to, say, 1000 and reduce sleep 3600 to sleep 10, then run docker compose up -d again.

    File compose.yaml

    services:
      nginx:
        image: nginx:1.30.8
        container_name: nginx-hardened-proxy
        ports:
          - "127.0.0.1:8443:443"
          - "127.0.0.1:8080:80"
        volumes:
          - ./conf/nginx.conf:/etc/nginx/nginx.conf:ro
          - ./certs:/etc/nginx/certs:ro
          - ./logs:/var/log/nginx
        depends_on:
          - backend
        restart: unless-stopped
    
      backend:
        image: traefik/whoami:v1.12.0
        restart: unless-stopped
    
      logrotate:
        image: alpine:3.24.4
        pid: "container:nginx-hardened-proxy"
        volumes:
          - ./logs:/logs
        entrypoint: ["/bin/sh", "-c"]
        command:
          - |
            while true; do
              for f in access error; do
                if [ -f /logs/$$f.log ] && [ $$(wc -c < /logs/$$f.log) -gt 10485760 ]; then
                  for i in 4 3 2 1; do
                    [ -f /logs/$$f.log.$$i ] && mv /logs/$$f.log.$$i /logs/$$f.log.$$((i+1))
                  done
                  mv /logs/$$f.log /logs/$$f.log.1
                  for p in /proc/[0-9]*; do
                    if grep -q 'nginx: master' $$p/cmdline 2>/dev/null; then
                      kill -USR1 $$(basename $$p)
                    fi
                  done
                fi
              done
              sleep 3600
            done
        depends_on:
          nginx:
            condition: service_started
        restart: unless-stopped
    docker compose up -d
    docker compose ps

    Expected output (illustrative: the exact format may vary)

    NAME                         IMAGE                      COMMAND                  SERVICE     STATUS         PORTS
    nginx-hardened-backend-1     traefik/whoami:v1.12.0     "/whoami"                backend     Up 1 minute    80/tcp
    nginx-hardened-logrotate-1   alpine:3.24.4              "/bin/sh -c 'while t…"   logrotate   Up 5 seconds
    nginx-hardened-proxy         nginx:1.30.8               "/docker-entrypoint.…"   nginx       Up 5 seconds   127.0.0.1:8080->80/tcp, 127.0.0.1:8443->443/tcp

Check that it works

  1. Check TLS, the redirect and the security headers

    Request only the headers. We use --insecure because the certificate is self-signed. You should see the headers defined with add_header. The sample output is abbreviated: the real response also includes other backend headers, such as Content-Type and Date.

    Then request port 8080 without following redirects: it should return a 301 to HTTPS. Finally, try to force TLS 1.1 with --tls-max 1.1: the command must exit with a non-zero code because we only allow TLS 1.2 and 1.3. The exact error message depends on your curl version and the TLS library it was built with; it may even reject the old-version flags locally, which also counts as a failure.

    curl --insecure --head https://127.0.0.1:8443/
    curl --head http://127.0.0.1:8080/
    curl --insecure --tlsv1.0 --tls-max 1.1 --head https://127.0.0.1:8443/

    Expected output (illustrative: the exact format may vary)

    HTTP/1.1 200 OK
    Strict-Transport-Security: max-age=300
    X-Content-Type-Options: nosniff
    X-Frame-Options: DENY
    Referrer-Policy: no-referrer
    Content-Security-Policy: default-src 'self'
    
    HTTP/1.1 301 Moved Permanently
    Location: https://127.0.0.1:8443/
    
    curl: (35) ...
  2. Check the request rate limit

    Fire 30 requests in parallel with --parallel so the bucket barely refills between them. With 5 r/s and a burst of 10 with no delay, the first ones pass and the rest receive the 429 code configured with limit_req_status. The exact numbers depend on timing; expect roughly 11-15 responses with 200 and the rest with 429.

    curl --insecure --silent --parallel --output /dev/null --write-out "%{http_code}\n" "https://127.0.0.1:8443/?[1-30]" | sort | uniq -c

    Expected output (illustrative: the exact format may vary)

         12 200
         18 429
  3. Review the logs

    The format includes $limit_req_status as the rl= field: PASSED for accepted requests and REJECTED for rejected ones. After the previous test you will see a mix of both; the last lines are usually rejections.

    tail -n 3 logs/access.log

    Expected output (illustrative: the exact format may vary)

    172.18.0.1 [01/Jan/2026:10:00:05 +0000] "GET /?28 HTTP/1.1" 429 162 "curl/8.16.0" rl=REJECTED
    172.18.0.1 [01/Jan/2026:10:00:05 +0000] "GET /?29 HTTP/1.1" 429 162 "curl/8.16.0" rl=REJECTED
    172.18.0.1 [01/Jan/2026:10:00:05 +0000] "GET /?30 HTTP/1.1" 429 162 "curl/8.16.0" rl=REJECTED
If something fails

The nginx container restarts in a loop with a certificate error.

Check that certs/server.crt and certs/server.key exist and are mounted at /etc/nginx/certs. See the exact reason in the container logs.

docker compose logs nginx

It returns 502 Bad Gateway.

The proxy cannot reach the backend. Confirm that the service is named backend (the name used in proxy_pass) and that it is running with docker compose ps.

The browser warns that the certificate is not trusted.

That is expected with a self-signed certificate. For real use, replace server.crt and server.key with ones from a CA and reload the service.

The security headers do not appear on a specific route.

If you define any add_header inside a location, that block stops inheriting those from the upper level. Repeat all the headers at the same level or look at add_header_inherit, available since version 1.29.3 (therefore also in 1.30.8).

Harden the setup

Keep the version up to date within the stable branch

Versions 1.30.7 and 1.30.8 shipped security fixes. Check the release notes from time to time and bump the image tag manually, with an exact number, instead of using a floating tag.

Do not expose the backend or the proxy more than necessary

The backend publishes no ports and the proxy listens only on 127.0.0.1. If you open it to the local network, do so by changing the address deliberately and consider restricting by IP with a firewall that you manage outside this lab.

Tune the rate limit to your real traffic

Add limit_req_dry_run on; in the http, server or location context to measure what would be rejected without blocking anyone: in that mode the status is recorded as DELAYED_DRY_RUN or REJECTED_DRY_RUN in $limit_req_status. Then set the final rate and burst and remove dry-run mode.

Protect the private key and do not mount the Docker socket

Keep certs/server.key at permissions 600, outside any repository, and always mount it read-only. For the same reason, the rotation service shares the process namespace instead of mounting /var/run/docker.sock, which would give an auxiliary container almost total control of the Docker daemon.

Clean-up: undo the lab

Remove everything you created

Run these commands from the nginx-hardened directory. First the containers, the network and the images used by the Compose services are stopped and removed (--rmi all); then you go up one level and delete the project directory, which contains certificates and logs.

docker compose down --rmi all --remove-orphans
cd ..
rm -rf nginx-hardened

What is verified

  • conf/nginx.conf: no automatic validator, review it by hand
  • compose.yaml syntax (YAML parser and Compose structure)
  • compose.yaml syntax (YAML parser and Compose structure)
  • Syntax of 8 command block(s) (bash -n in an isolated container, not executed)
  • Versions (4), options (11) and config keys (12) checked against 20 official documentation pages
  • Running the whole lab end to end: not executed

Automatic checks run on 25 November 2026. Items marked "·" were not executed: check them in your own environment.

Sources

Article generated with AI.larebelion

Byline

· Chief editor · English edition · London

“Pin the exact version, expose nothing by default, and read the release notes before every bump.”

Comments (0)

No comments yet. You can be the first.

Write a comment