Web servers and networking · Intermediate · 16 min
Reverse proxy and load balance several backends with Caddy
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · Caddy 2.11.9
You will put Caddy 2.11 in front of three backends on a private HTTPS hostname, choose a balancing policy, add passive and active health checks, route by path, and reload the config through Caddy's admin API.
On this page
One app process on one machine is a single point of failure. Put a proxy in front of several copies and it can share the traffic between them, stop sending requests to a copy that has broken, and send different paths to different services. Caddy does all of this inside its reverse_proxy directive, with HTTPS included.
In this tutorial you will run three small backends on one server and put Caddy in front of them on a private name, app.internal, with a certificate from Caddy's own local authority. You will try two balancing policies, watch Caddy route around a backend that has stopped (passive checks) and one that reports itself unwell (active checks), split traffic by path, and look at the JSON that Caddy builds from your Caddyfile. Every change is loaded through Caddy's admin API, so you can see that a bad config is refused while the old one keeps serving.
On real infrastructure the backends sit on other machines; you write their private addresses where this tutorial writes 127.0.0.1.
Step 1 · Prepare Caddy and three backends
Install Caddy 2.11 from the official repository first, as shown in /tutorials/automatic-https-with-caddy-2, and confirm the service is running:
systemctl status caddy --no-pagerYou want Active: active (running).
caddy versionThis prints v2.11.9 or a later 2.11 release.
Now write a backend. Python's standard library is enough, and Ubuntu ships python3. Each copy answers with its port, the path it received and the value of an X-App-Route header, so you can see exactly what Caddy sent it. It also answers /health, and reports 503 there while a file named down-<port> exists next to the script. That lets you make a backend look unwell without stopping it.
mkdir -p ~/caddy-lb-demo
cat > ~/caddy-lb-demo/backend.py <<'PY'
import os
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
port = int(sys.argv[1])
down_flag = os.path.join(os.path.dirname(os.path.abspath(__file__)), f"down-{port}")
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health":
healthy = not os.path.exists(down_flag)
status = 200 if healthy else 503
body = b"ok\n" if healthy else b"down\n"
else:
status = 200
route = self.headers.get("X-App-Route", "-")
body = f"backend {port} path={self.path} route={route}\n".encode()
self.send_response(status)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
PY
for port in 9101 9102 9103; do
nohup python3 ~/caddy-lb-demo/backend.py "$port" > /dev/null 2>&1 &
done
sleep 1The backends listen on 127.0.0.1 only, so nothing outside the server can reach them except through Caddy.
Check it worked
for port in 9101 9102 9103; do curl -s "http://127.0.0.1:$port/hello"; doneYou see three lines: backend 9101 path=/hello route=-, then the same for 9102 and 9103.
Step 2 · Proxy one hostname to all three and load it through the admin API
The next command replaces /etc/caddy/Caddyfile. Keep a copy of the current file first, so you can put it back at the end. On a server that already hosts sites with Caddy, add the new site block to your existing file instead of replacing it.
sudo cp /etc/caddy/Caddyfile /etc/caddy/Caddyfile.before-lb-demo
sudo tee /etc/caddy/Caddyfile > /dev/null <<'CADDY'
app.internal {
tls internal
reverse_proxy 127.0.0.1:9101 127.0.0.1:9102 127.0.0.1:9103 {
lb_policy round_robin
}
}
CADDY
caddy validate --config /etc/caddy/Caddyfile --adapter caddyfileThe output ends with Valid configuration.
app.internalis the site address. A name under.internalis reserved for private use and will never be a public domain, so no public certificate authority can issue for it.tls internaltells Caddy to sign the certificate with its own local authority instead of asking Let's Encrypt. Your staff's browsers will trust it only if you install that authority's root certificate on their machines.- Listing several upstreams on one
reverse_proxyline makes them a pool.lb_policy round_robinsends each request to the next one in turn. Without a policy line Caddy picks at random.
Caddy keeps an admin API on localhost:2019. sudo systemctl reload caddy works by running caddy reload, which posts your config to that API. You can post it yourself, which shows any error straight away:
curl --fail-with-body -sS -X POST http://localhost:2019/load \
-H 'Content-Type: text/caddyfile' \
--data-binary @/etc/caddy/CaddyfileNo output means the config was accepted. --data-binary keeps the line breaks the Caddyfile needs. Caddy then signs a certificate for app.internal, which takes a moment the first time.
The name app.internal is not in DNS yet, so the curl commands below use --resolve to point it at this server, and -k to accept the locally signed certificate.
Check it worked
for i in 1 2 3 4 5 6; do
curl -sk --resolve app.internal:443:127.0.0.1 https://app.internal/hello
done | sort | uniq -cEach backend answers twice: 2 backend 9101 ..., 2 backend 9102 ... and 2 backend 9103 ....
Step 3 · Choose a balancing policy
Round robin suits backends that are alike and requests that take similar time. Caddy has other policies; these are the ones you reach for most:
least_connpicks the backend with the fewest requests in flight. Use it when some requests are slow, such as report exports next to quick page loads.firstalways uses the first backend that is available and moves down the list only when it fails. That gives you a primary and spares.ip_hashandclient_ip_hashpick from the visitor's address, so one visitor keeps reaching one backend.cookiesets a cookie (namedlbby default) on the first response and sends later requests carrying it to the same backend. It keeps a visitor on one backend even when their address changes, which is common on mobile networks where many users share a few addresses and a phone hops between them.
Sticky policies are a stopgap for apps that keep sessions in memory. A shared session store is the better fix, because a backend can still fail and take its sessions with it.
Switch to cookie:
sudo tee /etc/caddy/Caddyfile > /dev/null <<'CADDY'
app.internal {
tls internal
reverse_proxy 127.0.0.1:9101 127.0.0.1:9102 127.0.0.1:9103 {
lb_policy cookie
}
}
CADDY
curl --fail-with-body -sS -X POST http://localhost:2019/load \
-H 'Content-Type: text/caddyfile' \
--data-binary @/etc/caddy/CaddyfileCheck it worked
Make five requests that save and send cookies, like a browser:
rm -f ~/caddy-lb-demo/cookies.txt
for i in 1 2 3 4 5; do
curl -sk --resolve app.internal:443:127.0.0.1 \
-c ~/caddy-lb-demo/cookies.txt -b ~/caddy-lb-demo/cookies.txt \
https://app.internal/hello
done | sort | uniq -c
grep -cw lb ~/caddy-lb-demo/cookies.txtAll five requests reach the same backend, for example 5 backend 9102 path=/hello route=-; which one is chosen at random the first time. The last command prints 1, the lb cookie in the saved file. Delete the cookie file and run the loop again, and you may land on a different backend.
Step 4 · Let Caddy notice a backend that has stopped
By default Caddy does not remember failures. If a backend is down, the request that hit it gets a 502 error. Passive health checks change that: Caddy counts failed requests and leaves a backend out of the pool for a while.
fail_duration 10sturns passive checks on and says how long a failure is remembered. Production setups often use 30 seconds or more; this tutorial uses 10 so you do not wait long.max_fails 1marks the backend unavailable after one remembered failure.unhealthy_status 5xxalso counts a5xxanswer from the backend as a failure, not only a refused connection.lb_try_duration 5sandlb_try_interval 250mslet Caddy retry a request on another backend for up to five seconds when it cannot connect. The visitor sees a short delay instead of an error page. On slow or prepaid mobile data that matters: a page that fails has to be loaded again, and that costs the visitor data.
sudo tee /etc/caddy/Caddyfile > /dev/null <<'CADDY'
app.internal {
tls internal
reverse_proxy 127.0.0.1:9101 127.0.0.1:9102 127.0.0.1:9103 {
lb_policy round_robin
lb_try_duration 5s
lb_try_interval 250ms
fail_duration 10s
max_fails 1
unhealthy_status 5xx
}
}
CADDY
curl --fail-with-body -sS -X POST http://localhost:2019/load \
-H 'Content-Type: text/caddyfile' \
--data-binary @/etc/caddy/CaddyfileStop the backend on port 9103 and send six requests straight away:
pkill -f 'backend.py 9103'
sleep 1
for i in 1 2 3 4 5 6; do
curl -sk --resolve app.internal:443:127.0.0.1 -o /dev/null -w '%{http_code}\n' https://app.internal/hello
doneAll six print 200. The request that tried 9103 failed to connect, Caddy counted the failure and retried it on another backend.
The admin API reports what Caddy knows about each upstream:
curl -s http://localhost:2019/reverse_proxy/upstreams | python3 -m json.toolThe entry for 127.0.0.1:9103 shows "fails": 1. The other two show 0. num_requests counts requests in flight at that moment, so it is usually 0.
Check it worked
Start the backend again and wait for the failure to expire:
nohup python3 ~/caddy-lb-demo/backend.py 9103 > /dev/null 2>&1 &
sleep 11
for i in 1 2 3 4 5 6; do
curl -sk --resolve app.internal:443:127.0.0.1 https://app.internal/hello
done | sort | uniq -cAll three backends appear again in the counts. Passive checks only learn from real traffic, so a backend that fails quietly between requests is not noticed until a visitor's request hits it. Active checks cover that gap.
Step 5 · Add active health checks
With active checks, Caddy requests a health URL on every backend on a timer, whether or not visitors are arriving, and removes any backend that does not answer as expected. Keep the passive settings too: each kind catches failures the other misses.
sudo tee /etc/caddy/Caddyfile > /dev/null <<'CADDY'
app.internal {
tls internal
reverse_proxy 127.0.0.1:9101 127.0.0.1:9102 127.0.0.1:9103 {
lb_policy round_robin
lb_try_duration 5s
lb_try_interval 250ms
health_uri /health
health_interval 2s
health_timeout 1s
health_status 200
fail_duration 10s
max_fails 1
unhealthy_status 5xx
}
}
CADDY
curl --fail-with-body -sS -X POST http://localhost:2019/load \
-H 'Content-Type: text/caddyfile' \
--data-binary @/etc/caddy/Caddyfilehealth_uri /healthis the path Caddy requests on each backend. Point it at a route in your app that checks what the app needs, such as its database connection, and answers quickly.health_interval 2sruns the check every two seconds. The default is 30 seconds; two is short so you can watch it happen. Pick a value that notices failures fast enough for you without flooding your logs.health_timeout 1scounts a slow answer as a failure.health_status 200is the status a healthy backend must return. It also accepts a class such as2xx.
Make the backend on 9102 report itself unwell. It keeps running and still answers normal requests, but /health now returns 503:
touch ~/caddy-lb-demo/down-9102
curl -s -w '%{http_code}\n' http://127.0.0.1:9102/health
sleep 5
for i in 1 2 3 4 5 6; do
curl -sk --resolve app.internal:443:127.0.0.1 https://app.internal/hello
done | sort | uniq -cThe direct request prints down and 503. The six requests through Caddy are shared between 9101 and 9103 only. No visitor request had to fail for Caddy to drop 9102; the timer found it.
Check it worked
Mark it healthy again:
rm ~/caddy-lb-demo/down-9102
sleep 5
for i in 1 2 3 4 5 6; do
curl -sk --resolve app.internal:443:127.0.0.1 https://app.internal/hello
done | sort | uniq -cbackend 9102 is back in the counts. This is also how you take a backend out of rotation for maintenance: make its health route fail, wait one interval, and work on it while Caddy sends traffic elsewhere.
Step 6 · Route by path and set headers for the backend
Often one hostname fronts more than one service. Say the API runs on 9101 and 9102 and a reporting service runs on 9103. handle and handle_path blocks split the traffic:
handle /reports/*matches the path and passes it on unchanged, so the backend receives/reports/q3.handle_path /api/*matches the same way but strips the matched prefix first, so the backend receives/usersfor a request to/api/users. Use it when the backend does not know it lives under a prefix.- A final
handlewith no path catches everything else.
Caddy tries handle blocks with a path before the catch-all, and only one block runs for each request.
header_up sets a request header on the way to the backend. Caddy already sets X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host, and passes the visitor's Host header through unchanged. This config adds X-App-Route so each service can tell which route it was reached through.
sudo tee /etc/caddy/Caddyfile > /dev/null <<'CADDY'
app.internal {
tls internal
handle_path /api/* {
reverse_proxy 127.0.0.1:9101 127.0.0.1:9102 {
lb_policy round_robin
lb_try_duration 5s
lb_try_interval 250ms
health_uri /health
health_interval 2s
health_timeout 1s
fail_duration 10s
unhealthy_status 5xx
header_up X-App-Route api
}
}
handle /reports/* {
reverse_proxy 127.0.0.1:9103 {
header_up X-App-Route reports
}
}
handle {
respond "No service at this path" 404
}
}
CADDY
curl --fail-with-body -sS -X POST http://localhost:2019/load \
-H 'Content-Type: text/caddyfile' \
--data-binary @/etc/caddy/Caddyfile
sleep 3If a backend expects requests addressed to its own name rather than the public one, add header_up Host {upstream_hostport} inside its reverse_proxy block.
Check it worked
curl -sk --resolve app.internal:443:127.0.0.1 https://app.internal/api/users
curl -sk --resolve app.internal:443:127.0.0.1 https://app.internal/api/users
curl -sk --resolve app.internal:443:127.0.0.1 https://app.internal/reports/q3
curl -sk --resolve app.internal:443:127.0.0.1 -w ' (%{http_code})\n' https://app.internal/otherYou see four lines, something like:
backend 9101 path=/users route=api
backend 9102 path=/users route=api
backend 9103 path=/reports/q3 route=reports
No service at this path (404)The API requests alternate between 9101 and 9102 and arrive without the /api prefix. The reports request keeps its full path. Anything else gets the 404.
Step 7 · Read the JSON config and test a bad change
Caddy's native config format is JSON. The Caddyfile is converted to JSON by an adapter, and the admin API stores and serves the JSON. Seeing it helps when a Caddyfile does not do what you expected.
caddy adapt --config /etc/caddy/Caddyfile --adapter caddyfile --pretty > ~/caddy-lb-demo/adapted.json
grep -n -A4 '"active"' ~/caddy-lb-demo/adapted.jsonThe handle_path block has become a route with a rewrite handler that strips /api, followed by a reverse_proxy handler. The health check settings sit under health_checks, with active and passive sections. Durations are written in nanoseconds, so 2s appears as 2000000000.
The running config is available from the API too. This prints the first part of it:
curl -s http://localhost:2019/config/ | python3 -m json.tool | head -n 20Now try a change with a mistake in it. Write it to a separate file, so the real Caddyfile stays correct:
cat > ~/caddy-lb-demo/broken.Caddyfile <<'CADDY'
app.internal {
tls internal
reverse_proxy 127.0.0.1:9101 {
lb_policy round_robbin
}
}
CADDY
curl -s -X POST http://localhost:2019/load \
-H 'Content-Type: text/caddyfile' \
--data-binary @$HOME/caddy-lb-demo/broken.Caddyfile \
-w '\nHTTP %{http_code}\n'The response is a JSON error naming the unknown policy, followed by HTTP 400. Caddy refused the config and kept the one it had.
Check it worked
curl -sk --resolve app.internal:443:127.0.0.1 https://app.internal/reports/q3You still get backend 9103 path=/reports/q3 route=reports. Running caddy validate before every load catches this kind of mistake earlier, and systemctl reload caddy gives you the same protection, because it uses the same API.
The admin API accepts changes from any program on the server without a password. On a server where other people or untrusted code run, read the admin endpoint section of the Caddy docs and move it to a Unix socket with restricted permissions.
Step 8 · Clean up
Stop the backends, put your original Caddyfile back and load it, then remove the demo folder:
pkill -f 'caddy-lb-demo/backend.py'
sudo mv /etc/caddy/Caddyfile.before-lb-demo /etc/caddy/Caddyfile
curl --fail-with-body -sS -X POST http://localhost:2019/load \
-H 'Content-Type: text/caddyfile' \
--data-binary @/etc/caddy/Caddyfile
rm -rf ~/caddy-lb-demoCaddy keeps the local authority and the app.internal certificate in its data folder. They do no harm, and Caddy reuses the authority for any other tls internal site.
Check it worked
pgrep -f 'caddy-lb-demo/backend.py' || echo "no backends running"
grep -c app.internal /etc/caddy/Caddyfile || trueThe first line prints no backends running and the second prints 0.
Next steps
- Serve a public site with certificates from a public authority in
/tutorials/automatic-https-with-caddy-2. - Compare the same job in Nginx, where open-source health checks are passive only:
/tutorials/load-balance-with-nginx-upstream. - When a backend misbehaves behind the proxy, trace it with
/tutorials/debug-a-slow-or-failing-website-with-curl.
Related tutorials
- Write Nginx location blocks that match what you expectYou will build a practice Nginx 1.30 server where every location block labels its responses, predict which block answers each of twelve URLs, check your answers with curl, and fix the alias, regex-order and proxy_pass mistakes that catch most people out.
- Write a server firewall with nftablesYou will write one /etc/nftables.conf with a default-drop input chain, rate-limited SSH, named address sets, counters and logging, and load it over SSH behind a timer that undoes it if you lose your connection.
- Watch a TCP connection open and close with tcpdumpYou will capture a curl request to a local web server with tcpdump on Ubuntu 26.04, read its handshake, data and teardown line by line, see the reset a closed port sends, and save, filter and rotate captures as pcap files.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials