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
On this page
- Why a TLS-terminating proxy
- What the proxy configuration does
- Lab steps
- The same setup on a public server
- Check your understanding
- Apply it
- Review prompt
Lessons of CD Strategies
- Delivery, deployment and rollout strategies: how each one fails Concept · 25 min
- Lab: a staged pipeline with approval and smoke tests Lab · 30 min
- Lab: a TLS-terminating reverse proxy in front of the service Lab · 30 min
- Lab: blue-green cutover and rollback behind the proxy Lab · 25 min
- Schema changes, feature flags, GitOps, traffic splitting and service meshes Concept · 30 min
- Check: choose and defend a release plan Knowledge check · 10 questions
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:
- 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+CHACHA20drops suites with plain RSA key exchange, which Nginx's defaultHIGH:!aNULL:!MD5still allows (it matches the TLS 1.2 list of Mozilla's intermediate profile).http2 on;needs Nginx 1.25.1 or later; older versions uselisten 443 ssl http2. - Routing. Nginx picks the
serverblock whoseserver_namematches theHostheader, then thelocationwith the longest matching prefix. Soapp.lab.test/api/...goes to the API,app.lab.test/...to the web service, and every path onapi.lab.testto the API. - Timeouts.
proxy_read_timeout(60 seconds by default) is how long Nginx waits for the upstream to answer; when it runs out the client gets504 Gateway Timeout. If one report export legitimately takes 90 seconds, raise the timeout only inlocation /api/v1/reports/; a site-wide five minutes would let hung requests tie up connections everywhere. - Forwarded headers and inheritance.
Host,X-Forwarded-ForandX-Forwarded-Prototell the service the original host, client address and scheme. Alocationinheritsproxy_set_headerlines from itsserveronly 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 onlyproxy_passand a timeout. If a location needs one extra header, it must repeat all of them. - Security headers.
Strict-Transport-Security: max-age=31536000(HSTS) tells browsers to use only HTTPS for this host for a year.alwaysadds it to error responses too; without it,add_headercovers only success and redirect codes. AddincludeSubDomainsonly when every subdomain serves HTTPS.client_max_body_sizelimits 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.
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 -vPebble version: v2.10.3
certbot 5.10.0
nginx version: nginx/1.31.10Step 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.
{
"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
}
}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": "[^"]*"'"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.
"""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()# 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;
}# 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
}
}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/ordersnginx: 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/ordersStep 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.
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 GETsAccount 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
6One 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.
# 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;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; }
}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 blanksnginx: 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=31536000The 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.
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)"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: 3cd "$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)"nginx now serves the renewed certificate
nginx reloads now: 4Step 7: stop everything. nginx -s quit stops gracefully: workers first finish their open requests. The rest stop by their saved PIDs.
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"lab stopped04. 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.
# 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# 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
06. Apply it
Take the lab further:
- Add a third host,
admin.lab.test, to the certificate withcertbot certonly --expand, and route it to a new upstream. - Add
location /api/v2/that needs one extra header, and check withbackend.pythat 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
- Let's Encrypt: Challenge types
- Certbot user guide: webroot, renewal and hooks
- Pebble: a small ACME test server
- nginx documentation: ngx_http_proxy_module
- nginx documentation: proxy_set_header (inheritance)
- nginx documentation: ngx_http_v2_module (http2 directive)
- nginx documentation: add_header
- Mozilla SSL Configuration Generator
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.