Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 3

Lab: a TLS-terminating reverse proxy in front of the service

Put Nginx in front of two services with host and path routing, get a certificate over ACME HTTP-01 from a local test CA with certbot, add HSTS and forwarded headers, and prove that renewal reloads Nginx through a deploy hook.

Contentsand lesson path

What you will learn

  • Configure a reverse proxy such as Nginx to route by host and path, terminate TLS with an automatically renewed ACME certificate, pass forwarded headers and sane timeouts, and switch traffic between two upstream releases.

Prerequisites: Cloud Basics, Continuous Integration

01. Why a TLS-terminating proxy

Application servers such as a Python or Node.js process are built to run business logic, not to face the internet directly. A reverse proxy such as Nginx, HAProxy or Envoy sits between clients and those processes and takes over three jobs:

  • TLS termination: the proxy holds the certificate, does the TLS handshake with each client and forwards plain HTTP to the services over a private network.
  • Buffering: the proxy reads a response from the service quickly and sends it to a slow client at the client's pace, so a phone on a weak connection does not hold a service worker busy.
  • Routing: one proxy sends requests to different upstreams by host name (api.example.com) or by path (/api/).

In this lab you build all three on your own machine. Nginx routes two host names and one path to two small services, and certbot gets a real certificate over ACME, the protocol Let's Encrypt uses, from Pebble, a test CA that the Let's Encrypt team publishes for exactly this purpose. Pebble is for testing only: browsers do not trust it, and its root certificate changes every time it starts.

02. What the proxy configuration does

The lab splits the configuration into a port-80 server (http.conf), shared TLS and proxy settings (tls-common.conf) and two HTTPS servers (tls.conf). The choices in it:

  1. TLS versions and ciphers. Only TLS 1.2 and 1.3 are allowed. Full TLS 1.3 handshakes use forward secrecy; for TLS 1.2, ECDHE+AESGCM:ECDHE+CHACHA20 drops suites with plain RSA key exchange, which Nginx's default HIGH:!aNULL:!MD5 still allows (it matches the TLS 1.2 list of Mozilla's intermediate profile). http2 on; needs Nginx 1.25.1 or later; older versions use listen 443 ssl http2.
  2. Routing. Nginx picks the server block whose server_name matches the Host header, then the location with the longest matching prefix. So app.lab.test/api/... goes to the API, app.lab.test/... to the web service, and every path on api.lab.test to the API.
  3. Timeouts. proxy_read_timeout (60 seconds by default) is how long Nginx waits for the upstream to answer; when it runs out the client gets 504 Gateway Timeout. If one report export legitimately takes 90 seconds, raise the timeout only in location /api/v1/reports/; a site-wide five minutes would let hung requests tie up connections everywhere.
  4. Forwarded headers and inheritance. Host, X-Forwarded-For and X-Forwarded-Proto tell the service the original host, client address and scheme. A location inherits proxy_set_header lines from its server only if it defines none of its own, and never from a sibling location. That is why the shared lines sit at server level and the locations set only proxy_pass and a timeout. If a location needs one extra header, it must repeat all of them.
  5. Security headers. Strict-Transport-Security: max-age=31536000 (HSTS) tells browsers to use only HTTPS for this host for a year. always adds it to error responses too; without it, add_header covers only success and redirect codes. Add includeSubDomains only when every subdomain serves HTTPS. client_max_body_size limits upload size.

03. Lab steps

Step 1: get the tools. You need Linux or WSL with Bash, curl, OpenSSL, Python 3.11 or later and Nginx 1.25.1 or later on your PATH. Nothing runs as root: Nginx runs as your user on ports above 1024. The commands download Pebble and its DNS helper, Pebble's own HTTPS certificate, and certbot into a virtual environment.

Bash · Step 1: Pebble, certbot and versions
mkdir -p proxy-lab/bin proxy-lab/pebble && cd proxy-lab && export LAB="$PWD"
REL=https://github.com/letsencrypt/pebble/releases/download/v2.10.3
for t in pebble pebble-challtestsrv; do
  curl -fsSL "$REL/$t-linux-amd64.tar.gz" | tar -xz -C bin --strip-components=3
done
chmod +x bin/pebble bin/pebble-challtestsrv   # the archives ship them as mode 644
RAW=https://raw.githubusercontent.com/letsencrypt/pebble/v2.10.3/test/certs
for f in pebble.minica.pem localhost/cert.pem localhost/key.pem; do
  curl -fsSLo "pebble/$(basename "$f")" "$RAW/$f"   # Pebble's own HTTPS identity
done
python3 -m venv certbot-venv
certbot-venv/bin/pip install -q --disable-pip-version-check certbot==5.10.0
ln -s ../certbot-venv/bin/certbot bin/certbot
export PATH="$LAB/bin:$PATH"
pebble -version | cut -d' ' -f1-3
certbot --version
nginx -v
Expected output (your Nginx version may differ)
Pebble version: v2.10.3
certbot 5.10.0
nginx version: nginx/1.31.10

Step 2: start the test CA. Save Pebble's configuration. httpPort 5002 is where Pebble sends its HTTP-01 checks, so in this lab port 5002 plays the role of port 80. pebble-challtestsrv answers DNS queries with 127.0.0.1, so the names app.lab.test and api.lab.test lead Pebble to your Nginx. PEBBLE_VA_NOSLEEP=1 and PEBBLE_WFE_NONCEREJECT=0 turn off the random delays and errors Pebble adds to test clients.

JSON · proxy-lab/pebble/config.json
{
  "pebble": {
    "listenAddress": "127.0.0.1:14000",
    "managementListenAddress": "127.0.0.1:15000",
    "certificate": "pebble/cert.pem",
    "privateKey": "pebble/key.pem",
    "httpPort": 5002,
    "tlsPort": 5001,
    "ocspResponderURL": "",
    "externalAccountBindingRequired": false
  }
}
Bash · Step 2: start Pebble and its DNS helper
cd "$LAB"
# DNS for the lab: every name resolves to 127.0.0.1 (IPv6 answers switched off)
pebble-challtestsrv -defaultIPv6 "" -dnsserver 127.0.0.1:8053 \
  -management 127.0.0.1:8055 -http01 "" -https01 "" -tlsalpn01 "" -doh "" \
  > pebble/dns.log 2>&1 &
echo $! > pebble/dns.pid
PEBBLE_VA_NOSLEEP=1 PEBBLE_WFE_NONCEREJECT=0 \
  pebble -config pebble/config.json -dnsserver 127.0.0.1:8053 > pebble/pebble.log 2>&1 &
echo $! > pebble/pebble.pid
CA=(--cacert pebble/pebble.minica.pem)
until curl -s "${CA[@]}" -o /dev/null https://127.0.0.1:14000/dir; do sleep 1; done
curl -s "${CA[@]}" https://127.0.0.1:14000/dir | grep -o '"newOrder": "[^"]*"'
Expected output
"newOrder": "https://127.0.0.1:14000/order-plz"

Step 3: start two services and the port-80 server. backend.py answers every request with its own name and the headers it received, so you can see where each request went. The main nginx.conf only keeps files and logs under proxy-lab/nginx; http.conf is the port-80 server from the callout above. The redirect keeps :8443 because the lab's HTTPS port is not 443.

Python · proxy-lab/backend.py
"""Tiny upstream for the lab: answers every GET with what it received."""
import json
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer

NAME, PORT = sys.argv[1], int(sys.argv[2])


class Echo(BaseHTTPRequestHandler):
    def do_GET(self):
        seen = {"backend": NAME, "path": self.path, "host": self.headers["Host"],
                "proto": self.headers["X-Forwarded-Proto"]}
        body = (json.dumps(seen) + "\n").encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass


HTTPServer(("127.0.0.1", PORT), Echo).serve_forever()
Nginx · proxy-lab/nginx/conf/nginx.conf
# Lab-only main file: runs nginx as your user with everything under $LAB/nginx
worker_processes 1;
pid logs/nginx.pid;
error_log logs/error.log notice;   # notice level records each reload
events { worker_connections 256; }
http {
  access_log logs/access.log;
  client_body_temp_path temp/body;
  proxy_temp_path temp/proxy;
  fastcgi_temp_path temp/fastcgi;
  uwsgi_temp_path temp/uwsgi;
  scgi_temp_path temp/scgi;
  include conf.d/*.conf;
}
Nginx · proxy-lab/nginx/conf/conf.d/http.conf
# Port 80 in production. Pebble checks HTTP-01 on port 5002, so the lab uses that.
server {
  listen 127.0.0.1:5002;
  server_name app.lab.test api.lab.test;

  location /.well-known/acme-challenge/ {
    root www/acme;          # certbot --webroot writes the challenge files here
  }
  location / {
    return 301 https://$host:8443$request_uri;   # production: https://$host$request_uri
  }
}
Bash · Step 3: services, config test, start Nginx
cd "$LAB"
python3 backend.py web 9101 & echo $! > web.pid
python3 backend.py api 9102 & echo $! > api.pid
mkdir -p nginx/logs nginx/temp nginx/www/acme
ngx() { nginx -p "$LAB/nginx" -c conf/nginx.conf -e logs/error.log "$@"; }
ngx -t 2>&1 | sed "s#$LAB#\$LAB#"
ngx
sleep 1
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' \
  --resolve app.lab.test:5002:127.0.0.1 http://app.lab.test:5002/orders
Expected output
nginx: the configuration file $LAB/nginx/conf/nginx.conf syntax is ok
nginx: configuration file $LAB/nginx/conf/nginx.conf test is successful
301 https://app.lab.test:8443/orders

Step 4: get the certificate. certbot's webroot method writes the token into www/acme, which the port-80 server already serves, so Nginx keeps running. --deploy-hook is saved with the certificate and runs once when it is first issued and again after every successful renewal; here it reloads Nginx, which otherwise keeps serving the old certificate from memory. The --config-dir inside Nginx's conf directory plays the role of /etc/letsencrypt. REQUESTS_CA_BUNDLE makes certbot trust Pebble's API, which a real CA does not need.

Bash · Step 4: certbot over HTTP-01
cd "$LAB" && mkdir -p le
export REQUESTS_CA_BUNDLE="$LAB/pebble/pebble.minica.pem"   # trust Pebble's API
LE=(--config-dir "$LAB/nginx/conf/letsencrypt" --work-dir "$LAB/le/work"
    --logs-dir "$LAB/le/logs" --server https://127.0.0.1:14000/dir)
HOOK="nginx -p $LAB/nginx -c conf/nginx.conf -e logs/error.log -s reload"
certbot certonly "${LE[@]}" --non-interactive --agree-tos \
  --register-unsafely-without-email --deploy-hook "$HOOK" \
  --webroot -w "$LAB/nginx/www/acme" -d app.lab.test -d api.lab.test \
  > le/certonly.out 2>&1
grep -E '^(Account registered|Successfully received)' le/certonly.out
ls nginx/conf/letsencrypt/live/app.lab.test/
openssl x509 -noout -ext subjectAltName \
  -in nginx/conf/letsencrypt/live/app.lab.test/cert.pem
grep -c 'acme-challenge.*Pebble-VA' nginx/logs/access.log   # Pebble's validation GETs
Expected output (the file list order can differ with your locale)
Account registered.
Successfully received certificate.
cert.pem
chain.pem
fullchain.pem
privkey.pem
README
X509v3 Subject Alternative Name: critical
    DNS:app.lab.test, DNS:api.lab.test
6

One certificate covers both names. The last number counts Pebble's requests for the challenge files in the access log: it checked each name from three simulated locations, as Let's Encrypt does from several networks. fullchain.pem (your certificate plus the intermediate) is the file Nginx needs for ssl_certificate.

Step 5: add the HTTPS servers. Save the two files below, test the configuration and reload. Then fetch Pebble's current root certificate so curl can verify the chain, and send requests by host and path. --resolve points the lab names at 127.0.0.1 without editing /etc/hosts.

Nginx · proxy-lab/nginx/conf/tls-common.conf
# Shared by both HTTPS servers (included at server level)
listen 127.0.0.1:8443 ssl;                      # 443 in production
http2 on;                                       # nginx 1.25.1 and later
ssl_certificate     letsencrypt/live/app.lab.test/fullchain.pem;
ssl_certificate_key letsencrypt/live/app.lab.test/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE+AESGCM:ECDHE+CHACHA20;        # TLS 1.2: ECDHE suites only
add_header Strict-Transport-Security "max-age=31536000" always;
client_max_body_size 10m;

# A location inherits these only if it sets no proxy_set_header itself
proxy_http_version 1.1;
proxy_set_header Connection "";
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_connect_timeout 5s;
proxy_read_timeout 60s;
Nginx · proxy-lab/nginx/conf/conf.d/tls.conf
upstream web_backend { server 127.0.0.1:9101; keepalive 16; }
upstream api_backend { server 127.0.0.1:9102; keepalive 16; }

server {                                # host app.lab.test: routed by path
  server_name app.lab.test;
  include tls-common.conf;
  location / { proxy_pass http://web_backend; }
  location /api/ { proxy_pass http://api_backend; }
  location /api/v1/reports/ {
    proxy_pass http://api_backend;
    proxy_read_timeout 120s;            # only the slow report exports wait longer
  }
}

server {                                # host api.lab.test: everything to the API
  server_name api.lab.test;
  include tls-common.conf;
  location / { proxy_pass http://api_backend; }
}
Bash · Step 5: reload and test host and path routing
cd "$LAB"
ngx -t 2>&1 | tail -1 | sed "s#$LAB#\$LAB#"
ngx -s reload && sleep 1
curl -s --cacert pebble/pebble.minica.pem -o pebble/root.pem \
  https://127.0.0.1:15000/roots/0       # the root that signed your certificate
C=(--cacert pebble/root.pem --resolve app.lab.test:8443:127.0.0.1
   --resolve api.lab.test:8443:127.0.0.1)
curl -s "${C[@]}" https://app.lab.test:8443/orders
curl -s "${C[@]}" https://app.lab.test:8443/api/orders
curl -s "${C[@]}" https://api.lab.test:8443/orders
curl -sI "${C[@]}" https://app.lab.test:8443/ | grep -iE '^(HTTP|strict)' \
  | sed 's/[[:space:]]*$//'      # HEAD request; strip trailing blanks
Expected output
nginx: configuration file $LAB/nginx/conf/nginx.conf test is successful
{"backend": "web", "path": "/orders", "host": "app.lab.test", "proto": "https"}
{"backend": "api", "path": "/api/orders", "host": "app.lab.test", "proto": "https"}
{"backend": "api", "path": "/orders", "host": "api.lab.test", "proto": "https"}
HTTP/2 501
strict-transport-security: max-age=31536000

The path decides on app.lab.test and the host decides on api.lab.test, and each service sees the original Host and https as the scheme. The HEAD request shows two more things: the connection used HTTP/2, and backend.py, which only implements GET, answered 501, yet the HSTS header is present, because of always.

Step 6: prove that renewal works. The reload count starts at 2: the deploy hook reloaded Nginx when the certificate was issued in step 4, and you reloaded it yourself in step 5. certbot renew --dry-run runs a full renewal without saving the result; by default it skips deploy hooks, and --run-deploy-hooks runs them too, so you can test the reload. --no-random-sleep-on-renew skips the random delay (up to a few minutes) that certbot adds outside a terminal to spread scheduled renewals. Then force a real renewal and check that Nginx serves the new certificate.

Bash · Step 6: dry run with the deploy hook
cd "$LAB"
reloads() { grep -c 'SIGHUP' nginx/logs/error.log; }
echo "nginx reloads so far: $(reloads)"
certbot renew "${LE[@]}" --no-random-sleep-on-renew --dry-run --run-deploy-hooks \
  > le/dry-run.out 2>&1
grep -E '^Simulating' le/dry-run.out
grep -o 'live/.*(success)' le/dry-run.out
sleep 1 && echo "nginx reloads now: $(reloads)"
Expected output
nginx reloads so far: 2
Simulating renewal of an existing certificate for app.lab.test and api.lab.test
live/app.lab.test/fullchain.pem (success)
nginx reloads now: 3
Bash · Step 6: a real renewal reaches Nginx
cd "$LAB"
serial() { openssl s_client -connect 127.0.0.1:8443 -servername app.lab.test \
  < /dev/null 2> /dev/null | openssl x509 -noout -serial; }
BEFORE=$(serial)
certbot renew "${LE[@]}" --no-random-sleep-on-renew --force-renewal -q && sleep 1
[ "$BEFORE" != "$(serial)" ] && echo "nginx now serves the renewed certificate"
echo "nginx reloads now: $(reloads)"
Expected output
nginx now serves the renewed certificate
nginx reloads now: 4

Step 7: stop everything. nginx -s quit stops gracefully: workers first finish their open requests. The rest stop by their saved PIDs.

Bash · Step 7: stop Nginx, the services and Pebble
cd "$LAB"
ngx -s quit
for p in web.pid api.pid pebble/pebble.pid pebble/dns.pid; do kill "$(cat "$p")"; done
echo "lab stopped"
Expected output
lab stopped

04. The same setup on a public server

On a real server the names resolve in public DNS, ports 80 and 443 are open, and certbot talks to Let's Encrypt. Only a few lines change; the commands and lines below are a configuration to apply, not output from this lab. Most certbot packages install a systemd timer or cron job that runs certbot renew twice a day; it renews only certificates close to expiry, and the deploy hook stored with the certificate reloads Nginx. Run certbot renew --dry-run after every change to the proxy or firewall, and alert on certificate expiry, so that a broken renewal is found weeks before users see an error. certbot also has an --nginx method that edits the configuration for you; webroot keeps the configuration under your control.

Bash · public server (apply on your host; not run here)
# On a server whose public DNS names app.example.com and api.example.com point at it
sudo mkdir -p /var/www/acme
sudo certbot certonly --webroot -w /var/www/acme \
  -d app.example.com -d api.example.com --deploy-hook "systemctl reload nginx"
sudo certbot renew --dry-run      # against the Let's Encrypt staging CA
systemctl list-timers | grep -i certbot   # the renewal timer most packages install
Nginx · lines that differ on a public server (not run here)
# conf.d/http.conf
listen 80;
server_name app.example.com api.example.com;
location /.well-known/acme-challenge/ { root /var/www/acme; }
location / { return 301 https://$host$request_uri; }

# tls-common.conf
listen 443 ssl;
ssl_certificate     /etc/letsencrypt/live/app.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;

05. Check your understanding

Practice check · 3 questions

Header inheritance, HSTS and renewal hooks

Three questions on the proxy configuration and the certificate renewal from the lab.

Q1. Shared `proxy_set_header` lines (Host, X-Forwarded-For) sit at `server` level. You add `location /exports/` with `proxy_pass` and its own `proxy_set_header X-Export 1;`. What reaches the backend on `/exports/`?
Q2. Why add the `always` parameter to `add_header Strict-Transport-Security "max-age=31536000"`?
Q3. On a server, the deploy hook saved with the certificate has a typo: `systemctl reload ngnix`. `certbot renew --dry-run` reports success. Weeks later the timer renews the certificate for real. What happens when the old certificate expires?
Practice only: not graded, not saved, not evidence.

06. Apply it

Take the lab further:

  • Add a third host, admin.lab.test, to the certificate with certbot certonly --expand, and route it to a new upstream.
  • Add location /api/v2/ that needs one extra header, and check with backend.py that you repeated the shared headers.
  • Stop Nginx and run the dry run again: read the error certbot gives when the CA cannot reach port 80.
  • On a server with a public name, repeat the setup against Let's Encrypt staging (--test-cert) before production.

07. Review prompt

Without looking back, explain how Nginx chose the upstream for each of the three requests in step 5, why the shared proxy_set_header lines sit at server level, and what always changed in the HEAD response. Then describe the path from certbot renew to Nginx serving a new certificate, and what breaks if port 80 is closed.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check