Caddy's JSON Config & Admin API
The Caddyfile is a convenience. Caddy's native configuration is a JSON document, and a running Caddy exposes it through an admin API (by default on localhost:2019) where any part can be read, replaced or patched over HTTP. Changes apply immediately and gracefully, are validated first, and are rejected as a whole if invalid. That makes Caddy easy to drive from deployment tools, service discovery or a control plane, without templating config files.
The shape of the JSON
{
"admin": { "listen": "localhost:2019" },
"logging": { "logs": { "default": { "level": "INFO" } } },
"apps": {
"http": {
"servers": {
"main": {
"listen": [":443"],
"routes": [
{ "match": [ { "host": ["shop.example"], "path": ["/api/*"] } ],
"handle": [ { "handler": "reverse_proxy", "upstreams": [ { "dial": "10.0.1.11:8080" } ] } ] }
]
}
}
},
"tls": { "automation": { "policies": [ { "issuers": [ { "module": "acme" } ] } ] } }
}
}A server has routes; each route has optional match sets and a list of handlers, run in order. Every Caddyfile directive maps onto this (caddy adapt shows how). Any object can carry an @id, which gives it a stable address in the API: /id/<name>/… instead of a long path with array indexes.
| Request | Effect |
|---|---|
GET /config/ |
the whole running config |
GET /config/apps/http/servers/main/listen |
one part, by path |
POST /load |
replace the entire config (what caddy reload does) |
POST /config/<path> |
append to an array, or create |
PUT /config/<path> |
create, or insert into an array at an index |
PATCH /config/<path> |
replace an existing value |
DELETE /config/<path> |
remove it |
GET/PATCH /id/<id>/… |
the same, addressed through an @id |
Driving a running Caddy
cat > app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200); self.end_headers(); self.wfile.write(f"{sys.argv[2]}\n".encode())
def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 blue & python3 app.py 9002 green &
for p in 9001 9002; do for i in $(seq 50); do curl -s 127.0.0.1:$p/ > /dev/null && break; sleep 0.1; done; done
cat > caddy.json <<'EOF'
{
"admin": {"listen": "localhost:2019"},
"apps": {"http": {"servers": {"main": {
"listen": [":8080"],
"routes": [
{"@id": "app", "handle": [{"handler": "reverse_proxy", "upstreams": [{"dial": "127.0.0.1:9001"}]}]}
]
}}}}
}
EOF
caddy start --config caddy.json > caddy.log 2>&1 && echo "caddy started"
API=localhost:2019; J='Content-Type: application/json'
echo "serving: $(curl -s 127.0.0.1:8080/)"
echo "upstreams: $(curl -s $API/id/app/handle/0/upstreams)"
echo "--- switch blue -> green with one PATCH:"
curl -s -X PATCH -H "$J" -d '[{"dial":"127.0.0.1:9002"}]' $API/id/app/handle/0/upstreams
echo "serving: $(curl -s 127.0.0.1:8080/)"
echo "--- insert a maintenance route in front (PUT at index 0):"
curl -s -X PUT -H "$J" $API/config/apps/http/servers/main/routes/0 \
-d '{"match":[{"path":["/admin/*"]}],"handle":[{"handler":"static_response","status_code":503,"body":"admin is down for maintenance\n"}]}'
curl -s -w '[%{http_code}]\n' 127.0.0.1:8080/admin/users
echo "routes now: $(curl -s $API/config/apps/http/servers/main/routes | jq length)"
echo "--- an invalid config is rejected as a whole:"
curl -s -X POST -H "$J" $API/load -d '{"apps":{"http":{"servers":{"main":{"listen":[":8080"],"routes":[{"handle":[{"handler":"reverse_prox"}]}]}}}}}' | jq -r .error | sed 's/: loading module/:\n loading module/'
echo "serving: $(curl -s 127.0.0.1:8080/)"
echo "--- a browser page on another origin can't use the API:"
curl -s -H 'Origin: http://evil.example' $API/config/ | jq -r .error
caddy stop > /dev/null 2>&1; kill %1 %2caddy started
serving: blue
upstreams: [{"dial":"127.0.0.1:9001"}]
--- switch blue -> green with one PATCH:
serving: green
--- insert a maintenance route in front (PUT at index 0):
admin is down for maintenance
[503]
routes now: 2
--- an invalid config is rejected as a whole:
loading config: loading new config: loading http app module: provision http: server main: setting up route handlers: route 0: loading handler modules: position 0:
loading module 'reverse_prox': unknown module: http.handlers.reverse_prox
serving: green
--- a browser page on another origin can't use the API:
client is not allowed to access from origin 'http://evil.example'
The PATCH moved all traffic from blue to green in place: no file was edited, nothing was reloaded by hand, and in-flight requests finished on the old upstream. A blue/green switch, a canary weight change or adding a backend found by service discovery is a single API call. The failed /load left the running configuration untouched, and the error said exactly which module failed (here a typo in the handler name).
Persistence and safety
- Changes made through the API are in memory. Caddy also autosaves the last config to its config directory (
autosave.json), andcaddy run --resumestarts from it. If you drive Caddy through the API, decide which is the source of truth: the API (with--resume), or a file that your tool rewrites and loads, but not both. - Protect the admin endpoint. It can change everything, including making Caddy proxy to anywhere. Keep it on
localhost(the default) or a UNIX socket (admin unix//run/caddy-admin.sock), never on a public address. Caddy enforces an origin check, which is why the request with a foreignOriginheader (what a malicious web page in a browser would send) was refused.admin offdisables it entirely, but thencaddy reloadandcaddy stopcan't work either. - Config ETags (
Etag/If-Matchon/config/) protect against two tools overwriting each other's changes.
The Caddyfile and the API together
A common split: the Caddyfile (or a generated JSON file) defines the static parts, loaded by caddy reload --config Caddyfile on deploy; a controller then PATCHes only the parts that change at runtime, addressed by @id. In a Caddyfile you can't set @id directly; generate JSON for those parts, or address them by path.
Test yourself
You POST a new route to /config/apps/http/servers/main/routes. Where does it end up?
- At the start of the list
- At the end of the list, after any catch-all route, so it may never match
- It replaces the routes
- It is rejected
What happens when /load receives an invalid configuration?
- Caddy stops
- The request fails with an error and the old configuration keeps running
- Caddy loads the valid parts
- Caddy restarts
Why does the admin API check the Origin header?
- For CORS caching
- So that a web page in someone's browser can't send requests to the local admin endpoint and reconfigure Caddy
- To support HTTP/2
- For logging