← Start of tutorial

WIUNIX ACADEMY

HAProxy with Let’s Encrypt and validated certificate renewal

Page 3 of 5. Review the earlier steps and prerequisites before continuing.

YOUR SYSTEM. YOUR STEPS.

Where are you working?

Choose your OS and version. The prerequisites, commands and troubleshooting follow your environment.

Rocky Linux 10.2Reviewed against official documentation ·

USE YOUR OWN VALUES

Configure this tutorial

Set the example values for your environment; related explanations and copy panels update together. Never enter passwords, private keys or tokens. Values stay in this tab and are not sent to the server or share links. Check actual DNS, certificates and network policy before running commands.

Different IP addresses, domains or ports? Open the settings below, change the values and select “Apply to tutorial”, then copy the updated commands.

Set values for my environment7 editable values
13

LET’S BUILD

Assemble and validate the first protected PEM

Check server purpose, trust chain, hostname, one day remaining, matching key and equality of the cert.pem/fullchain first certificate before assembly. Write a private same-filesystem candidate and atomically install the first PEM only when no target exists. Keep ACME symlink targets private; never grant the challenge user access to keys.

bash

Bash on dedicated edge VM; external checks noted in text

set -eu
sudo python3 - <<'PY'
import os, subprocess, tempfile
from pathlib import Path
os.umask(0o077)
root=Path('/srv/academy-haproxy-tls')
lineage=root/'acme/config/live/app.example.com'
target=root/'certs/app.example.com.pem'
if target.exists() or target.is_symlink():raise SystemExit('Initial PEM already exists')
def run(*args):
    return subprocess.run(args,check=True,capture_output=True).stdout
run('openssl','x509','-in',str(lineage/'cert.pem'),'-checkend','86400','-noout')
run('openssl','verify','-CAfile','/etc/pki/tls/certs/ca-bundle.crt',
    '-untrusted',str(lineage/'chain.pem'),'-purpose','sslserver',
    '-verify_hostname','app.example.com',str(lineage/'cert.pem'))
if run('openssl','x509','-in',str(lineage/'cert.pem'),'-pubkey','-noout') != run('openssl','pkey','-in',str(lineage/'privkey.pem'),'-pubout'):
    raise SystemExit('Certificate/key mismatch')
if run('openssl','x509','-in',str(lineage/'cert.pem'),'-outform','DER') != run('openssl','x509','-in',str(lineage/'fullchain.pem'),'-outform','DER'):
    raise SystemExit('fullchain leaf does not match cert.pem')
fd,name=tempfile.mkstemp(dir=target.parent,prefix='.initial-')
with os.fdopen(fd,'wb') as f:
    f.write((lineage/'fullchain.pem').read_bytes()+b'\n'+(lineage/'privkey.pem').read_bytes())
    f.flush(); os.fsync(f.fileno())
os.replace(name,target)
print('Initial protected PEM assembled; TLS config not yet loaded')
PY
How do I know it worked?

A root-owned0600 PEM exists; the HTTP bootstrap continues serving challenges unchanged.

14

LET’S BUILD

Save a complete TLS candidate without overwriting the live config

Confirm both private backends serve the same application and /health/ready returns200 only when dependencies are ready. Both must accept Host app.example.com. Session/state handling belongs to the application. Paste the next file into the new candidate; keep the running bootstrap intact. The configuration sets no HSTS preload/includeSubDomains and exposes no administrative socket.

bash

Bash on dedicated edge VM; external checks noted in text

set -eu
for ip in '10.77.0.21' '10.77.0.22'; do
  status=$(curl --noproxy '*' --silent --show-error --output /dev/null --write-out '%{http_code}' --max-time 10 -H 'Host: app.example.com' "http://$ip:8080/health/ready")
  test "$status" = 200 || { echo "Backend $ip readiness is $status; STOP" >&2; exit 1; }
done
test ! -e '/srv/academy-haproxy-tls/haproxy.tls.cfg'
test ! -L '/srv/academy-haproxy-tls/haproxy.tls.cfg'
sudo install -m 0644 /dev/null '/srv/academy-haproxy-tls/haproxy.tls.cfg'
sudo nano '/srv/academy-haproxy-tls/haproxy.tls.cfg'
How do I know it worked?

Both readiness endpoints return200; the separate TLS candidate is ready to edit.

15

LET’S BUILD

TLS, trusted headers and readiness checks

This replaces the entire candidate file. Forwarded is removed, while X-Forwarded-* values are set from the direct connection. Do not add option forwardfor on top of this policy. Backends must trust only the actual private source address used by HAProxy, not every RFC1918 client.

text · /srv/academy-haproxy-tls/haproxy.tls.cfg

File on the dedicated edge VM

global
  log stdout format raw local0
  user haproxy
  group haproxy
  ssl-default-bind-options ssl-min-ver TLSv1.2

defaults
  log global
  mode http
  option httplog
  timeout connect 5s
  timeout client 30s
  timeout server 30s
  timeout http-request 10s

frontend public_http
  bind 192.0.2.10:80
  acl known_host hdr(host) -i app.example.com app.example.com:80
  http-request deny deny_status 421 unless known_host
  acl acme_path path_beg /.well-known/acme-challenge/
  http-request redirect prefix https://app.example.com code 308 unless acme_path
  use_backend acme_webroot if acme_path

backend acme_webroot
  server challenge 127.0.0.1:8888 check

frontend public_https
  bind 192.0.2.10:443 ssl crt /srv/academy-haproxy-tls/certs/app.example.com.pem alpn h2,http/1.1
  acl known_host hdr(host) -i app.example.com app.example.com:443
  http-request deny deny_status 421 unless known_host
  http-request del-header Forwarded
  http-request del-header X-Forwarded-For
  http-request del-header X-Forwarded-Proto
  http-request del-header X-Forwarded-Host
  http-request del-header X-Forwarded-Port
  http-request del-header X-Real-IP
  http-request set-header X-Forwarded-For %[src]
  http-request set-header X-Forwarded-Proto https
  http-request set-header X-Forwarded-Host app.example.com
  http-request set-header X-Forwarded-Port 443
  default_backend app_nodes

backend app_nodes
  balance roundrobin
  option httpchk
  http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host app.example.com
  http-check expect status 200
  server app_a 10.77.0.21:8080 check inter 2s fall 2 rise 2
  server app_b 10.77.0.22:8080 check inter 2s fall 2 rise 2
How do I know it worked?

Candidate has both public listeners, one loopback challenge backend and two checked application nodes.

16

LET’S BUILD

Validate, replace and gracefully reload

The first backup is the HTTP-only bootstrap. Validate the full TLS candidate before any replacement; a failed check leaves it untouched. Copy to a same-filesystem temporary name then rename. If reload fails, restore the bootstrap deliberately before investigating; the next recovery panel provides commands. A successful reload still requires the independent TLS probe.

bash

Bash on dedicated edge VM; external checks noted in text

set -eu
sudo /usr/sbin/haproxy -c -f '/srv/academy-haproxy-tls/haproxy.tls.cfg'
sudo test ! -e '/srv/academy-haproxy-tls/haproxy.bootstrap.cfg'
sudo test ! -L '/srv/academy-haproxy-tls/haproxy.bootstrap.cfg'
sudo cp -a '/srv/academy-haproxy-tls/haproxy.cfg' '/srv/academy-haproxy-tls/haproxy.bootstrap.cfg'
sudo install -m 0644 '/srv/academy-haproxy-tls/haproxy.tls.cfg' '/srv/academy-haproxy-tls/haproxy.cfg.next'
sudo mv '/srv/academy-haproxy-tls/haproxy.cfg.next' '/srv/academy-haproxy-tls/haproxy.cfg'
sudo systemctl reload academy-haproxy.service
sudo systemctl --no-pager status academy-haproxy.service
How do I know it worked?

HAProxy validates, the master gracefully reloads and the dedicated service remains active.

17

LET’S BUILD

Verify trust and backend selection independently

Run the first curl from outside the edge without --resolve and without -k. Its normal CA validation must succeed for app.example.com. The local resolve probe tests this specific listener using the same hostname. Send spoofed proxy headers and inspect only a private controlled application endpoint/log: the observed Forwarded must be absent and X-Forwarded-For must be the direct client, with https and port443. Never expose a debug header endpoint publicly.

Take one backend out of readiness during a controlled application maintenance window, wait at least two failed checks and confirm repeated requests reach the healthy node. Restore readiness and observe two successful checks. Do not kill an unrelated process or infer failover from a single200; readiness, session state and real response markers matter.

bash

Bash on dedicated edge VM; external checks noted in text

set -eu
curl --noproxy '*' --fail --show-error 'https://app.example.com/'
curl --noproxy '*' --fail --show-error --resolve 'app.example.com:443:192.0.2.10' \
  -H 'Forwarded: for=198.51.100.99;proto=http' \
  -H 'X-Forwarded-For: 198.51.100.99' 'https://app.example.com/'
openssl s_client -connect '192.0.2.10:443' -servername 'app.example.com' \
  -verify_hostname 'app.example.com' -verify_return_error -CAfile /etc/pki/tls/certs/ca-bundle.crt </dev/null
How do I know it worked?

Normal CA/hostname validation succeeds; controlled backend evidence shows the sanitized direct-client headers and healthy-node routing.

18

LET’S BUILD

Install a root-only renewal deploy hook

The next Python file is a deploy hook, not an ACME client. It checks the exact lineage, locks concurrent deployments, validates certificate/name/key and a private candidate config, then preserves the previous PEM and atomically swaps the candidate. Validation or issuance failure cannot replace the healthy PEM. A reload exception restores the previous PEM and attempts a validated reload, then exits with failure. A failure of that recovery remains visible for the operator; it cannot guarantee service recovery under every fault.

bash

Bash on dedicated edge VM; external checks noted in text

set -eu
test ! -e '/srv/academy-haproxy-tls/deploy.py'
test ! -L '/srv/academy-haproxy-tls/deploy.py'
sudo install -m 0700 /dev/null '/srv/academy-haproxy-tls/deploy.py'
sudo nano '/srv/academy-haproxy-tls/deploy.py'
How do I know it worked?

Only root can edit/execute the new hook; the complete file follows.

19

LET’S BUILD

Validated atomic deployment

Complete file. Capture failures in the dedicated service journal; never log key bytes. A deploy-hook failure occurs after Certbot may already have renewed its lineage: repair and rerun this hook manually with the reviewed lineage rather than forcing a new order.

python · /srv/academy-haproxy-tls/deploy.py

File on the dedicated edge VM

#!/usr/bin/python3
"""Root-only deploy hook; never print private material."""
import fcntl
import os
from pathlib import Path
import subprocess
import tempfile

ROOT = Path("/srv/academy-haproxy-tls")
DOMAIN = "app.example.com"
LINEAGE = ROOT / "acme/config/live" / DOMAIN
PEM = ROOT / "certs" / (DOMAIN + ".pem")
CONFIG = ROOT / "haproxy.cfg"
CAFILE = "/etc/pki/tls/certs/ca-bundle.crt"

def run(*args):
    return subprocess.run(args, check=True, capture_output=True).stdout

def main():
    if os.geteuid() != 0:
        raise SystemExit("root required")
    if Path(os.environ.get("RENEWED_LINEAGE", "")).resolve() != LINEAGE.resolve():
        raise SystemExit("unexpected lineage; no changes")
    os.umask(0o077)
    with (ROOT / "deploy.lock").open("a") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        cert, chain, key = [LINEAGE / n for n in ("cert.pem", "chain.pem", "privkey.pem")]
        run("openssl", "x509", "-in", str(cert), "-checkend", "86400", "-noout")
        run("openssl", "verify", "-CAfile", CAFILE, "-untrusted", str(chain),
            "-purpose", "sslserver", "-verify_hostname", DOMAIN, str(cert))
        public = run("openssl", "x509", "-in", str(cert), "-pubkey", "-noout")
        if public != run("openssl", "pkey", "-in", str(key), "-pubout"):
            raise SystemExit("certificate/key mismatch; no changes")
        if not PEM.is_file() or PEM.is_symlink():
            raise SystemExit("initial reviewed PEM must already exist")
        if run("openssl", "x509", "-in", str(cert), "-outform", "DER") != run("openssl", "x509", "-in", str(LINEAGE / "fullchain.pem"), "-outform", "DER"):
            raise SystemExit("fullchain leaf does not match cert.pem")
        old = PEM.read_bytes()
        candidate = None
        changed = False
        try:
            fd, name = tempfile.mkstemp(prefix=".candidate-", suffix=".pem", dir=PEM.parent)
            candidate = Path(name)
            with os.fdopen(fd, "wb") as output:
                output.write((LINEAGE / "fullchain.pem").read_bytes() + b"\n" + key.read_bytes())
                output.flush()
                os.fsync(output.fileno())
            # Replace only the one exact crt path in a private validation config.
            config = CONFIG.read_text(encoding="utf-8")
            if config.count("crt " + str(PEM)) != 1:
                raise SystemExit("unexpected crt binding; no changes")
            with tempfile.TemporaryDirectory(prefix="validate-", dir=ROOT) as work:
                check = Path(work) / "haproxy.cfg"
                check.write_text(config.replace("crt " + str(PEM), "crt " + str(candidate)), encoding="utf-8")
                run("/usr/sbin/haproxy", "-c", "-f", str(check))
            backup = PEM.with_suffix(".previous.pem")
            fd, name = tempfile.mkstemp(prefix=".backup-", dir=PEM.parent)
            with os.fdopen(fd, "wb") as output:
                output.write(old)
                output.flush()
                os.fsync(output.fileno())
            os.replace(name, backup)
            os.replace(candidate, PEM)
            changed = True
            run("/usr/sbin/haproxy", "-c", "-f", str(CONFIG))
            run("/usr/bin/systemctl", "reload", "academy-haproxy.service")
        except BaseException:
            if changed:
                fd, name = tempfile.mkstemp(prefix=".rollback-", dir=PEM.parent)
                with os.fdopen(fd, "wb") as output:
                    output.write(old)
                    output.flush()
                    os.fsync(output.fileno())
                os.replace(name, PEM)
                run("/usr/sbin/haproxy", "-c", "-f", str(CONFIG))
                run("/usr/bin/systemctl", "reload", "academy-haproxy.service")
            raise
        finally:
            if candidate is not None:
                candidate.unlink(missing_ok=True)
    print("validated PEM deployed; verify the public certificate separately")

if __name__ == "__main__":
    main()
How do I know it worked?

The file compiles; it accepts only the dedicated production lineage and retains a protected previous PEM.

Explore all tutorials ↗