23.5. Hosting Applications Behind a Reverse Proxy

The application now moves to center stage: a systemd service under a dedicated account, reachable only through the edge, with headers that carry the client's identity across the proxy hop. The same section pattern covers PHP, because PHP-FPM is the same idea in FastCGI clothing: a pool of workers behind a socket the web server talks to.

23.5.1. Running an Application as a Dedicated Systemd Service

The application answers a small, fixed contract, which is what lets the rest of this chapter test the infrastructure around it rather than the application itself:

Path Response
/ an HTML page reporting the release, derived client address and scheme, host, and request identifier
/healthz JSON: status, release, database reachability, visit count
/counter plain text: the visit counter after incrementing
/api/echo JSON: everything the service derived about the request - peer, client, scheme, host, identifiers, headers
/slow a response that takes five seconds, for timeout testing
anything else 404
/ws (separate service, port 8081) WebSocket echo

It is a Python standard-library program plus the websockets library for the echo companion - no framework, no dependencies beyond the interpreter. Any HTTP application takes its place in a real deployment; the listing is complete so the exercise is reproducible exactly as captured.

Two identities are involved. The web servers run as www-data; the application gets its own system account so the two can never read each other's secrets. Create it, on app1, as john:

$ sudo useradd --system --home-dir /var/lib/handbook --create-home --shell /usr/sbin/nologin --user-group handbook

The command prints nothing. The common useradd options are tabulated in Chapter 5; the two that matter specifically here are --system, which allocates from the system range, and --user-group, which creates a matching handbook group. The --shell /usr/sbin/nologin setting makes an interactive login impossible - the account exists to own files and run one process, nothing else. Confirm what was created:

$ getent passwd handbook
handbook:x:999:989::/var/lib/handbook:/usr/sbin/nologin

The application code lives under /srv in per-release directories, with a current symlink selecting what runs; Section 23.6.2 turns that symlink into the deployment and rollback mechanism. Save the program in the workspace as fixtures/app/app.py - file contents for app1:

#!/usr/bin/env python3
"""Small application used by the chapter 23 lab.

It listens on TCP and on a Unix socket, stores a visit counter in SQLite,
and reports the request identity it derived from the immediate peer and the
forwarded headers.  Standard library only.
"""

import asyncio
import json
import os
import pwd
import sqlite3
import time
import uuid
from datetime import datetime, timezone
from urllib.parse import urlsplit

RELEASE = os.path.basename(os.path.dirname(os.path.realpath(__file__)))
DB_PATH = os.environ.get("DB_PATH", "/var/lib/handbook/app.db")
LOG_PATH = os.environ.get("LOG_PATH", "/var/log/handbook/app.log")
SOCKET_PATH = os.environ.get("SOCKET", "/run/handbook/app.sock")
TRUSTED_PROXIES = {
    item.strip()
    for item in os.environ.get("TRUSTED_PROXIES", "").split(",")
    if item.strip()
}

REASONS = {
    200: "OK",
    403: "Forbidden",
    404: "Not Found",
    405: "Method Not Allowed",
    500: "Internal Server Error",
}


def init_db():
    connection = sqlite3.connect(DB_PATH)
    connection.execute(
        "CREATE TABLE IF NOT EXISTS visits ("
        "id INTEGER PRIMARY KEY CHECK (id = 1), "
        "count INTEGER NOT NULL)"
    )
    connection.execute(
        "INSERT OR IGNORE INTO visits (id, count) VALUES (1, 0)"
    )
    connection.commit()
    connection.close()


def db_state():
    connection = sqlite3.connect(DB_PATH)
    row = connection.execute(
        "SELECT count FROM visits WHERE id = 1"
    ).fetchone()
    connection.close()
    return int(row[0]) if row else 0


def increment():
    connection = sqlite3.connect(DB_PATH)
    connection.execute(
        "UPDATE visits SET count = count + 1 WHERE id = 1"
    )
    connection.commit()
    count = connection.execute(
        "SELECT count FROM visits WHERE id = 1"
    ).fetchone()[0]
    connection.close()
    return int(count)


def write_log(request_id, remote, path, status):
    stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    line = (
        f"{stamp} rid={request_id} remote={remote} "
        f"path={path} status={status} release={RELEASE}\n"
    )
    try:
        with open(LOG_PATH, "a", encoding="utf-8") as handle:
            handle.write(line)
    except OSError:
        pass


def response(status, body, request_id, content_type="text/plain; charset=utf-8"):
    if isinstance(body, str):
        body = body.encode("utf-8")
    head = [
        f"HTTP/1.1 {status} {REASONS.get(status, 'OK')}",
        "Server: handbook-app",
        f"Content-Length: {len(body)}",
        f"Content-Type: {content_type}",
        f"X-Request-ID: {request_id}",
        "Connection: close",
    ]
    return ("\r\n".join(head) + "\r\n\r\n").encode("ascii") + body


async def handle(reader, writer):
    peer = writer.get_extra_info("peername")
    peer_ip = "unix"
    if isinstance(peer, tuple) and peer:
        peer_ip = peer[0]
    if peer_ip.startswith("::ffff:"):
        peer_ip = peer_ip[7:]

    try:
        raw_head = await asyncio.wait_for(
            reader.readuntil(b"\r\n\r\n"), timeout=15
        )
    except (asyncio.IncompleteReadError, asyncio.TimeoutError):
        writer.close()
        await writer.wait_closed()
        return

    lines = raw_head.decode("iso-8859-1").split("\r\n")
    try:
        method, target, _version = lines[0].split(" ", 2)
    except ValueError:
        writer.write(response(405, "bad request line\n", "none"))
        await writer.drain()
        writer.close()
        await writer.wait_closed()
        return

    headers = {}
    for line in lines[1:]:
        if ":" in line:
            name, value = line.split(":", 1)
            headers[name.strip().lower()] = value.strip()

    try:
        length = int(headers.get("content-length", "0") or "0")
    except ValueError:
        length = 0
    body = b""
    if length:
        try:
            body = await asyncio.wait_for(
                reader.readexactly(length), timeout=15
            )
        except (asyncio.IncompleteReadError, asyncio.TimeoutError):
            writer.close()
            await writer.wait_closed()
            return

    path = urlsplit(target).path
    request_id = headers.get("x-request-id") or str(uuid.uuid4())
    forwarded_for = headers.get("x-forwarded-for")
    trusted = peer_ip in TRUSTED_PROXIES

    if forwarded_for and not trusted:
        write_log(request_id, peer_ip, path, 403)
        payload = (
            "untrusted forwarded header\n"
            f"peer={peer_ip}\n"
            "set X-Forwarded-For only through the configured proxy\n"
        )
        writer.write(response(403, payload, request_id))
        await writer.drain()
        writer.close()
        await writer.wait_closed()
        return

    if trusted and forwarded_for:
        client = forwarded_for.split(",")[0].strip()
        scheme = headers.get("x-forwarded-proto", "http")
        host = headers.get("x-forwarded-host") or headers.get("host", "")
    else:
        client = peer_ip
        scheme = "http"
        host = headers.get("host", "")

    if method not in ("GET", "HEAD"):
        status = 405
        payload = "method not allowed\n"
        content_type = "text/plain; charset=utf-8"
    elif path == "/healthz":
        try:
            count = db_state()
            status = 200
            payload = json.dumps(
                {
                    "status": "ok",
                    "release": RELEASE,
                    "database": "ok",
                    "visits": count,
                },
                sort_keys=True,
            ) + "\n"
        except sqlite3.Error as error:
            status = 500
            payload = json.dumps(
                {"status": "error", "database": str(error)}
            ) + "\n"
        content_type = "application/json"
    elif path == "/counter":
        status = 200
        payload = f"visits={increment()} release={RELEASE}\n"
        content_type = "text/plain; charset=utf-8"
    elif path == "/slow":
        await asyncio.sleep(5)
        status = 200
        payload = f"slow response release={RELEASE}\n"
        content_type = "text/plain; charset=utf-8"
    elif path == "/api/echo":
        status = 200
        payload = json.dumps(
            {
                "release": RELEASE,
                "peer": peer_ip,
                "client": client,
                "scheme": scheme,
                "host": host,
                "request_id": request_id,
                "forwarded_for": forwarded_for,
                "user_agent": headers.get("user-agent", ""),
                "body_bytes": len(body),
            },
            indent=2,
            sort_keys=True,
        ) + "\n"
        content_type = "application/json"
    elif path == "/":
        status = 200
        payload = (
            "<!doctype html>\n"
            "<html lang=\"en\"><head><meta charset=\"utf-8\">"
            "<title>Handbook application</title></head><body>\n"
            "<h1>Handbook application</h1>\n"
            f"<p>release={RELEASE}</p>\n"
            f"<p>client={client}</p>\n"
            f"<p>scheme={scheme}</p>\n"
            f"<p>host={host}</p>\n"
            f"<p>request_id={request_id}</p>\n"
            "</body></html>\n"
        )
        content_type = "text/html; charset=utf-8"
    else:
        status = 404
        payload = f"not found: {path}\n"
        content_type = "text/plain; charset=utf-8"

    write_log(request_id, client, path, status)
    writer.write(response(status, payload, request_id, content_type))
    await writer.drain()
    writer.close()
    await writer.wait_closed()


async def main():
    init_db()
    bind = os.environ.get("BIND", "0.0.0.0")
    port = int(os.environ.get("PORT", "8080"))
    tcp_server = await asyncio.start_server(
        handle, bind, port, reuse_address=True
    )

    try:
        os.unlink(SOCKET_PATH)
    except FileNotFoundError:
        pass
    unix_server = await asyncio.start_unix_server(handle, path=SOCKET_PATH)
    os.chmod(SOCKET_PATH, 0o660)
    try:
        gid = pwd.getpwnam("www-data").pw_gid
        os.chown(SOCKET_PATH, -1, gid)
    except KeyError:
        pass

    async with tcp_server, unix_server:
        await asyncio.Future()


if __name__ == "__main__":
    asyncio.run(main())

And the WebSocket companion, fixtures/app/ws.py:

#!/usr/bin/env python3
"""Minimal WebSocket echo service for the chapter 23 lab."""

import asyncio
import os

import websockets


async def echo(connection):
    async for message in connection:
        await connection.send(f"echo:{message}")


async def main():
    port = int(os.environ.get("WS_PORT", "8081"))
    async with websockets.serve(echo, "0.0.0.0", port):
        await asyncio.Future()


if __name__ == "__main__":
    asyncio.run(main())

The main program reads its whole configuration from environment variables - paths, bind address, port, and the set of proxy addresses whose forwarded headers it will believe. File contents for app1, fixtures/app/app.env:

DB_PATH=/var/lib/handbook/app.db
LOG_PATH=/var/log/handbook/app.log
SOCKET=/run/handbook/app.sock
BIND=0.0.0.0
PORT=8080
TRUSTED_PROXIES=192.168.234.11

TRUSTED_PROXIES is the single address of web2, the Nginx edge; its meaning is the subject of Section 23.5.3. The unit that ties account, code, and configuration together - file contents for app1, fixtures/app/handbook-app.service:

[Unit]
Description=Handbook application service
Documentation=https://example.invalid/handbook
After=network.target

[Service]
Type=simple
User=handbook
Group=handbook
SupplementaryGroups=www-data
EnvironmentFile=/etc/handbook/app.env
ExecStart=/usr/bin/python3 /srv/handbook/app/current/app.py
Restart=on-failure
RestartSec=2s
RuntimeDirectory=handbook
RuntimeDirectoryMode=0755
StateDirectory=handbook
StateDirectoryMode=0750
LogsDirectory=handbook
LogsDirectoryMode=0750
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes

[Install]
WantedBy=multi-user.target

And the echo companion's unit, fixtures/app/handbook-ws.service:

[Unit]
Description=Handbook WebSocket echo service
After=network.target

[Service]
Type=simple
User=handbook
Group=handbook
Environment=WS_PORT=8081
ExecStart=/usr/bin/python3 /srv/handbook/app/current/ws.py
Restart=on-failure
RestartSec=2s
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes

[Install]
WantedBy=multi-user.target

Three groups of directives do the work. User, Group, and SupplementaryGroups=www-data run the process as the dedicated account with the web server's group added - that group membership is what will let the Nginx worker reach the application's Unix socket in Section 23.5.2. EnvironmentFile supplies the configuration, kept in /etc/handbook at mode 0640 root:handbook, so the runtime's settings (and in real life, its secrets) are readable by the service and root alone. RuntimeDirectory, StateDirectory, and LogsDirectory make systemd create and own /run/handbook, /var/lib/handbook, and /var/log/handbook with the right permissions at every start - and under ProtectSystem=strict, which would otherwise make the whole hierarchy read-only, exactly those three directories are mounted writable for the unit. The rest of the hardening follows the unit-writing practice of Chapter 8.

Application release, state, and runtime layout

Figure 23.4. One release symlink away from rollback. The unit opens code through current, reads its configuration from /etc/handbook, and relies on systemd to create the runtime, state, and log directories it owns.

Deploy the two releases - the same file set under both names, which is exactly what a real deployment produces - the environment file, and the units, on app1, as john:

$ sudo install -d -o handbook -g handbook /srv/handbook/app/releases/20261122-a
$ sudo install -d -o handbook -g handbook /srv/handbook/app/releases/20261122-b
$ sudo install -m 0755 -o handbook -g handbook fixtures/app/app.py /srv/handbook/app/releases/20261122-a/app.py
$ sudo install -m 0755 -o handbook -g handbook fixtures/app/app.py /srv/handbook/app/releases/20261122-b/app.py
$ sudo install -m 0755 -o handbook -g handbook fixtures/app/ws.py /srv/handbook/app/releases/20261122-a/ws.py
$ sudo install -m 0755 -o handbook -g handbook fixtures/app/ws.py /srv/handbook/app/releases/20261122-b/ws.py
$ sudo ln -sfn /srv/handbook/app/releases/20261122-a /srv/handbook/app/current
$ sudo install -d -m 0750 -o root -g handbook /etc/handbook
$ sudo install -m 0640 -o root -g handbook fixtures/app/app.env /etc/handbook/app.env
$ sudo install -m 0644 fixtures/app/handbook-app.service /etc/systemd/system/handbook-app.service
$ sudo install -m 0644 fixtures/app/handbook-ws.service /etc/systemd/system/handbook-ws.service
$ sudo systemctl daemon-reload

Every command above is silent. Enable both units to start at boot and start them now:

$ sudo systemctl enable --now handbook-app handbook-ws
Created symlink '/etc/systemd/system/multi-user.target.wants/handbook-app.service' → '/etc/systemd/system/handbook-app.service'.
Created symlink '/etc/systemd/system/multi-user.target.wants/handbook-ws.service' → '/etc/systemd/system/handbook-ws.service'.

enable --now does both halves of activation: one Created symlink line per unit wires it into multi-user.target, and the services start immediately. Check the state, on app1, as john:

$ systemctl is-active handbook-app
active

And ask the service itself, through its loopback listener:

$ curl -sS http://127.0.0.1:8080/healthz
{"database": "ok", "release": "20261122-a", "status": "ok", "visits": 0}

The health endpoint reports the release the symlink selected, that the SQLite database under /var/lib/handbook opened, and the visit count - everything the proxy and the operator will rely on later. Look at the layout the unit produced, on app1, as john:

$ ls -ld /srv/handbook/app/current /var/lib/handbook
lrwxrwxrwx 1 root     root       37 Nov 22 17:02 /srv/handbook/app/current -> /srv/handbook/app/releases/20261122-a
drwxr-x--- 2 handbook handbook 4096 Nov 22 17:02 /var/lib/handbook

The symlink itself is root-owned - selecting a release is an administrator's decision - while the state directory belongs to the service account with no access for anyone else.

23.5.2. Unix Sockets, Loopback Listeners, and Backend Permissions

Where an application listens decides who can even attempt to connect, before any application-level check runs:

Bind target Who can connect Access control Use
0.0.0.0:port every host that can route to it firewall + application when the proxy is on another host
LAN address :port hosts on that network firewall + application same, with a smaller surface
127.0.0.1:port processes on the same host none needed proxy on the same host
Unix socket processes with permission on the socket file file ownership and mode same host; the tightest fit

The practice application binds 0.0.0.0:8080 because its proxy is on another machine, and also opens a Unix socket at /run/handbook/app.sock, which demonstrates the same-host case. It sets the socket's group to www-data and mode 0660 in its own code, so the decision is visible in one place. Check what that produced, on app1, as john:

$ sudo stat -c '%a %U:%G %n' /run/handbook/app.sock
660 handbook:www-data /run/handbook/app.sock

The file-level permission is the entire access control: owner handbook, group www-data, no access for others. Verify both sides of that line, on app1, as john:

$ sudo -u www-data curl --unix-socket /run/handbook/app.sock -sS http://localhost/healthz
{"database": "ok", "release": "20261122-a", "status": "ok", "visits": 0}
$ sudo -u nobody curl --max-time 3 --unix-socket /run/handbook/app.sock -sS http://localhost/healthz
curl: (7) Failed to connect to localhost port 80 after 0 ms: Could not connect to server

The www-data request succeeds because the account is in the socket's group; nobody is not, the kernel refuses the connect, and curl reports failure with exit status 7. curl --unix-socket replaces TCP with the socket path - the http://localhost/ URL supplies only the request line, not a connection.

For the TCP listener there is no file to chmod, so the boundary moves to the packet filter, using the nftables practice of Chapter 18. File contents for app1, /etc/nftables-ch23.nft:

table inet ch23 {
    chain input {
        type filter hook input priority 0; policy accept;
        iifname "eth1" ip saddr != 192.168.234.11 tcp dport 8080 drop
        iifname "eth1" ip saddr != 192.168.234.11 tcp dport 8081 drop
        iifname "eth1" ip saddr != 192.168.234.11 tcp dport 9000 drop
    }
}

On the practice interface, everything except the proxy's address is dropped for the three backend ports. Load it, on app1, as john:

$ sudo nft -f /etc/nftables-ch23.nft

The rule load prints nothing. Try the backend directly from the client, on client1, as john:

$ curl -sS --max-time 3 http://192.168.234.12:8080/
curl: (28) Connection timed out after 3002 milliseconds

The request dies silently after three seconds because a drop rule discards packets rather than refusing them - there is no connection-refused signal, just absence. That absence is worth demonstrating from the inside too: remove the table, on app1, as john:

$ sudo nft delete table inet ch23

And the same request now reaches the application, on client1, as john:

$ curl -sS --max-time 3 http://192.168.234.12:8080/
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>Handbook application</title></head><body>
<h1>Handbook application</h1>
<p>release=20261122-a</p>
<p>client=192.168.234.20</p>
<p>scheme=http</p>
<p>host=192.168.234.12:8080</p>
<p>request_id=cb9b3f8f-4453-47e7-9c39-475df1845e44</p>
</body></html>

With the filter gone, any host on the practice LAN can talk to the backend - including reading the page that should only ever be served through the edge. Restore the filter, on app1, as john:

$ sudo nft -f /etc/nftables-ch23.nft

Silent again, and the boundary is back. The two mechanisms compose: binding decides which interface carries the traffic, the filter decides which peer is welcome, and the application's own trust list (Section 23.5.3) decides which peer's headers to believe.

23.5.3. Forwarded Headers, Trusted Proxies, and WebSocket Connections

A proxy breaks one thing the application cares about: the peer address of the TCP connection is now the proxy's, not the client's. The fix is a set of conventional headers the proxy sets and the application interprets - but only from a peer it trusts, because any client can send those headers themselves:

  • X-Forwarded-For - the client address, with earlier proxies appended as a comma-separated list.
  • X-Forwarded-Proto - the scheme the client actually used, so a TLS-terminated backend still knows the request was HTTPS.
  • X-Forwarded-Host - the original Host.
  • X-Real-IP - a common single-address alternative to the list.
  • X-Request-ID - an identifier created at the edge and echoed back, which Section 23.6.1 uses to correlate logs.

The practice application enforces the trust rule in its own code: headers are honored when the connection's peer is in TRUSTED_PROXIES, and a forwarded header from anyone else earns a 403. The edge configuration does its half by overwriting the headers from the socket peer rather than appending to whatever the client sent. File contents for web2, fixtures/nginx/app.conf:

upstream handbook_app {
    server 192.168.234.12:8080;
    keepalive 8;
}

upstream handbook_ws {
    server 192.168.234.12:8081;
}

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    server_name app.handbook.test;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    http2 on;
    server_name app.handbook.test;

    ssl_certificate /etc/ssl/certs/handbook-wildcard.fullchain.pem;
    ssl_certificate_key /etc/ssl/private/handbook-wildcard.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers off;
    add_header Strict-Transport-Security "max-age=31536000" always;

    client_max_body_size 1m;

    location / {
        proxy_pass http://handbook_app;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Request-ID $request_id;
        proxy_set_header Connection "";
        proxy_connect_timeout 2s;
        proxy_read_timeout 2s;
    }

    location /ws {
        proxy_pass http://handbook_ws;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_set_header X-Request-ID $request_id;
        proxy_read_timeout 60s;
    }

    location = /healthz {
        proxy_pass http://handbook_app/healthz;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Request-ID $request_id;
        proxy_set_header Connection "";
        proxy_connect_timeout 2s;
        proxy_read_timeout 2s;
    }

    access_log /var/log/nginx/app.access.log handbook;
    error_log /var/log/nginx/app.error.log;
}

Line by line through the parts that are not repetition of the static site: the two upstream blocks name the backends so the proxy_pass targets survive address changes in one place, and keepalive 8 keeps a pool of idle connections to the application open. proxy_http_version 1.1 with Connection "" lets the upstream pool actually work by suppressing the hop-by-hop Connection: close of HTTP/1.0 proxying. The proxy_set_header lines are the trust boundary: X-Forwarded-For $remote_addr writes the edge's view of the client over anything the client claimed. The timeouts bound the backend: two seconds to connect, two to read, which Section 23.6.4 turns into a diagnosable 504. The /ws location is the WebSocket path: an upgrade request needs Upgrade and Connection: upgrade forwarded, which the map computes from whether the client actually sent an upgrade header, and a longer read timeout because a WebSocket is idle by design.

Deploy it, on web2, as john:

$ sudo install -m 0644 fixtures/nginx/app.conf /etc/nginx/sites-available/app.handbook.test.conf
$ sudo ln -sfn /etc/nginx/sites-available/app.handbook.test.conf /etc/nginx/sites-enabled/app.handbook.test.conf

The first two commands are silent. Then validate and activate as in Section 23.3.1 - sudo nginx -t, whose output is the two success lines already captured there, followed by sudo systemctl reload nginx, which prints nothing. Now look at what the application sees. On client1, as john:

$ curl -sS https://app.handbook.test/
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>Handbook application</title></head><body>
<h1>Handbook application</h1>
<p>release=20261122-a</p>
<p>client=192.168.234.20</p>
<p>scheme=https</p>
<p>host=app.handbook.test</p>
<p>request_id=236662c5c0407a7ba77e16579f8b82cc</p>
</body></html>

The client address is client1's own, and the scheme is https, even though the connection the application received was cleartext HTTP from web2 - the forwarded headers survived the hop and were believed because the peer was the trusted proxy. Try to lie, on client1, as john:

$ curl -sS -H 'X-Forwarded-For: 203.0.113.9' https://app.handbook.test/api/echo
{
  "body_bytes": 0,
  "client": "192.168.234.20",
  "forwarded_for": "192.168.234.20",
  "host": "app.handbook.test",
  "peer": "192.168.234.11",
  "release": "20261122-a",
  "request_id": "8bbb6435fb5c8ee7eed4879f210ffe01",
  "scheme": "https",
  "user_agent": "curl/8.14.1"
}

The spoofed 203.0.113.9 vanished: the edge overwrote X-Forwarded-For with the socket peer's address before the application ever saw the request. peer is web2 - the application knows who actually connected - and client is what the trusted proxy said. The application's own enforcement is visible from the backend host: a request that arrives without going through the proxy, carrying a forwarded header, is rejected. On app1, as john:

$ curl -sS -o /dev/null -w '%{http_code}\n' -H 'X-Forwarded-For: 203.0.113.9' http://127.0.0.1:8080/
403
$ curl -sS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/
200

Same listener, one header apart: loopback is not in TRUSTED_PROXIES, so a forwarded header there is a lie, and the application says so. The two rules together - overwrite at the edge, distrust elsewhere - are what make the header mean anything at all.

The WebSocket path carries the trust model over an upgraded connection. Install the client library on client1, as john, with sudo apt install python3-websockets; it pulls in nothing beyond the interpreter's own dependencies, and apt asks for the usual confirmation before installing it. Save the small client - file contents for client1, in the workspace as fixtures/ws/ws-client.py:

#!/usr/bin/env python3
import asyncio
import ssl
import sys

import websockets


async def main(url):
    context = ssl.create_default_context()
    async with websockets.connect(url, ssl=context) as connection:
        await connection.send("hello through nginx")
        print(await connection.recv())


if __name__ == "__main__":
    asyncio.run(main(sys.argv[1]))

The client verifies TLS through the same system trust store curl uses. Run it, on client1, as john:

$ python3 fixtures/ws/ws-client.py wss://app.handbook.test/ws
echo:hello through nginx

One line came back: the message traveled over TLS to the edge, was upgraded and forwarded to the echo service on app1, and returned. Finally, look at the headers the edge attaches to a proxied response, on client1, as john:

$ curl -sSI https://app.handbook.test/
HTTP/2 200
server: nginx
date: Sun, 22 Nov 2026 17:04:22 GMT
content-type: text/html; charset=utf-8
content-length: 310
x-request-id: 612eb94a6c539964d58abdc73b5594a6
strict-transport-security: max-age=31536000

Three things in one capture: the connection negotiated HTTP/2, the x-request-id the edge generated is visible to the client (and correlatable in Section 23.6.1), and the HSTS header from Section 23.4.4's policy is present on the proxied site exactly as on the static one.

23.5.4. PHP-FPM Pools and Application-Specific Resource Limits

PHP arrives as a pool manager: php-fpm keeps a set of worker processes, each handling one request at a time, and the web server forwards requests to the pool over FastCGI. The pool - not the web server and not php.ini - is where per-application limits belong, because every pool is one application's sandbox.

Install it on app1, as john, with sudo apt install php-fpm. The metapackage pulls php8.4-fpm, starts a default www pool on a Unix socket, and enables it at boot. Check the interpreter the pool runs, on app1, as john:

$ php -v
PHP 8.4.28 (cli) (built: Nov 18 2026 10:55:31) (NTS)
Copyright (c) The PHP Group
Built by Debian
Zend Engine v4.4.28, Copyright (c) Zend Technologies
    with Zend OPcache v8.4.28, Copyright (c), by Zend Technologies

The chapter's application pool listens on the practice LAN address with its client list restricted, so the web host can reach it while nothing else does. File contents for app1, fixtures/app/handbook-pool.conf:

[handbook]
user = www-data
group = www-data
listen = 192.168.234.12:9000
listen.allowed_clients = 192.168.234.11
pm = dynamic
pm.max_children = 2
pm.start_servers = 1
pm.min_spare_servers = 1
pm.max_spare_servers = 2
pm.max_requests = 50
pm.status_path = /fpm-status
ping.path = /fpm-ping
access.log = /var/log/php-handbook-access.log
slowlog = /var/log/php-handbook-slow.log
request_slowlog_timeout = 2s
catch_workers_output = yes
php_admin_value[memory_limit] = 64M
php_admin_value[upload_max_filesize] = 2M
php_admin_value[post_max_size] = 2M

The process manager settings say how the pool breathes:

pm mode Workers Fit
static a fixed number, always resident steady, known load; simplest memory accounting
dynamic starts at pm.start_servers, keeps between the spare bounds, never exceeds pm.max_children variable load; the mode used here
ondemand zero until a request, spawns and reaps rarely used pools; cold starts on first hit

pm.max_requests = 50 recycles a worker after fifty requests - cheap insurance against leaks in long-lived PHP code. slowlog records a stack trace for any request slower than two seconds, with catch_workers_output keeping worker stderr out of the main log. The three php_admin_value lines are pool-local PHP settings that the application cannot override at runtime, unlike values set in php.ini: this pool may allocate 64 MB and accept a 2 MB upload, and a different pool on the same host could allow ten times that without either seeing the other's limits.

Install the pool, test it, and restart the pool manager, on app1, as john. The install is silent; the test below is not:

$ sudo install -m 0644 fixtures/app/handbook-pool.conf /etc/php/8.4/fpm/pool.d/handbook.conf

php-fpm8.4 -tt tests the configuration and dumps every effective setting - including the untouched default www pool, omitted here. Selected output, the pool's own section and the verdict:

$ sudo php-fpm8.4 -tt
[22-Nov-2026 17:08:55] NOTICE: [handbook]
[22-Nov-2026 17:08:55] NOTICE:  user = www-data
[22-Nov-2026 17:08:55] NOTICE:  group = www-data
[22-Nov-2026 17:08:55] NOTICE:  listen = 192.168.234.12:9000
[22-Nov-2026 17:08:55] NOTICE:  listen.allowed_clients = 192.168.234.11
[22-Nov-2026 17:08:55] NOTICE:  pm = dynamic
[22-Nov-2026 17:08:55] NOTICE:  pm.max_children = 2
[22-Nov-2026 17:08:55] NOTICE:  pm.start_servers = 1
[22-Nov-2026 17:08:55] NOTICE:  pm.min_spare_servers = 1
[22-Nov-2026 17:08:55] NOTICE:  pm.max_spare_servers = 2
[22-Nov-2026 17:08:55] NOTICE:  pm.max_requests = 50
[22-Nov-2026 17:08:55] NOTICE:  pm.status_path = /fpm-status
[22-Nov-2026 17:08:55] NOTICE:  ping.path = /fpm-ping
[22-Nov-2026 17:08:55] NOTICE:  access.log = /var/log/php-handbook-access.log
[22-Nov-2026 17:08:55] NOTICE:  slowlog = /var/log/php-handbook-slow.log
[22-Nov-2026 17:08:55] NOTICE:  request_slowlog_timeout = 2s
[22-Nov-2026 17:08:55] NOTICE:  catch_workers_output = yes
[22-Nov-2026 17:08:55] NOTICE:  php_admin_value[post_max_size] = 2M
[22-Nov-2026 17:08:55] NOTICE:  php_admin_value[upload_max_filesize] = 2M
[22-Nov-2026 17:08:55] NOTICE:  php_admin_value[memory_limit] = 64M
[22-Nov-2026 17:08:55] NOTICE:
[22-Nov-2026 17:08:55] NOTICE: configuration file /etc/php/8.4/fpm/php-fpm.conf test is successful

Then restart the pool manager, on app1, as john:

$ sudo systemctl restart php8.4-fpm

Silent, like the other activation commands.

The pool's PHP script goes in /srv/php on the FPM host - file contents for app1, fixtures/php/index.php:

<?php
header('Content-Type: application/json');
if (isset($_GET['sleep'])) {
    sleep(min(5, max(0, (int) $_GET['sleep'])));
}
$payload = [
    'sapi' => php_sapi_name(),
    'pid' => getmypid(),
    'memory_limit' => ini_get('memory_limit'),
    'upload_max_filesize' => ini_get('upload_max_filesize'),
    'post_max_size' => ini_get('post_max_size'),
    'host' => $_SERVER['HTTP_HOST'] ?? '',
    'remote' => $_SERVER['REMOTE_ADDR'] ?? '',
    'document_root' => $_SERVER['DOCUMENT_ROOT'] ?? '',
];
echo json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), "\n";

It reports which server API handled it, its worker's process ID, the pool's limits, and the request identity the web server forwarded. Install it, on app1, as john; both install commands are silent:

$ sudo install -d -o www-data -g www-data /srv/php
$ sudo install -m 0644 -o www-data -g www-data fixtures/php/index.php /srv/php/index.php

Confirm the listener exists with the intended address, on app1, as john:

$ sudo ss -ltnp | grep :9000
LISTEN 0      4096   192.168.234.12:9000      0.0.0.0:*    users:(("php-fpm8.4",pid=23825,fd=12),("php-fpm8.4",pid=23824,fd=9))

The web side is one server block that hands .php requests to the pool. File contents for web2, fixtures/nginx/php.conf:

server {
    listen 80;
    server_name php.handbook.test;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    http2 on;
    server_name php.handbook.test;

    ssl_certificate /etc/ssl/certs/handbook-wildcard.fullchain.pem;
    ssl_certificate_key /etc/ssl/private/handbook-wildcard.key;
    ssl_protocols TLSv1.2 TLSv1.3;

    root /srv/php;
    index index.php;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass 192.168.234.12:9000;
    }

    access_log /var/log/nginx/php.access.log handbook;
    error_log /var/log/nginx/php.error.log;
}

snippets/fastcgi-php.conf is Debian's tested set of FastCGI parameters; the one that matters here is SCRIPT_FILENAME $document_root$fastcgi_script_name, which makes the FPM host open /srv/php/index.php - the same path must exist on the FPM host, which is why the script was installed on app1. Deploy, on web2, as john:

$ sudo install -m 0644 fixtures/nginx/php.conf /etc/nginx/sites-available/php.handbook.test.conf
$ sudo ln -sfn /etc/nginx/sites-available/php.handbook.test.conf /etc/nginx/sites-enabled/php.handbook.test.conf

Validate and activate exactly as before - sudo nginx -t printing the two success lines captured in Section 23.3.1, then sudo systemctl reload nginx, which is silent. Request the page, on client1, as john:

$ curl -sS https://php.handbook.test/
{
    "sapi": "fpm-fcgi",
    "pid": 23825,
    "memory_limit": "64M",
    "upload_max_filesize": "2M",
    "post_max_size": "2M",
    "host": "php.handbook.test",
    "remote": "192.168.234.20",
    "document_root": "/srv/php"
}

sapi fpm-fcgi proves the request ran in a pool worker, the limits are the pool's own three settings, and remote is client1's address as the edge forwarded it. Finally, watch the pool's concurrency limit actually bite. The script sleeps when asked; hold both workers for three seconds each and time the third request, on client1, as john:

$ seq 3 | xargs -P3 -I{} curl -fsS -o /dev/null -w '%{time_total}\n' 'https://php.handbook.test/?sleep=3' | sort -n | tail -n 1
6.053253

The pipeline is one logical load test: seq 3 numbers three jobs, xargs -P3 runs three curls concurrently, each writes its total time, and sort -n | tail -n 1 shows the slowest. Two workers absorbed the first two requests immediately; the third waited about three seconds for a free worker, finishing at roughly six. That is pm.max_children = 2 doing its job - and the shape of what a saturated PHP application looks like from the outside: not errors, but latency. Raise the limit only with the memory arithmetic in hand: max_children times memory_limit is the pool's worst-case resident memory (Chapter 9 covers the cgroup-level controls that make such budgets enforceable).