Docs pages

0004 — Embedded Caddy as the proxy

Status: accepted by the maintainer · Date: 2026-11-20

Context. Traefik idles ~80–120 MB and its label/config paths caused Dokploy bugs and CVEs; Caddy ~20–40 MB with an atomic JSON config API and automatic HTTPS.

Decision. Embed Caddy as a Go library in the agent; generate full JSON config from desired state; on-demand TLS gated by our DB. Fallback: official Caddy container controlled over a Unix-socket admin API.

Consequences. Zero extra containers on managed servers; +20–30 MB binary size. Validate idle RSS in Phase 0 Spike 1; switch to the fallback if over budget.


Addendum A — Upstream switches without a proxy reload

Status: accepted by the maintainer (plan 0004 Revision 11, 2026-11-24) · built in M3a step 6b.

Context. The first app-route design (plan 0004 step 6) gave every exposed app its own Caddy server and rebuilt the whole config on every route change, so a deploy switch was a caddy.Load. A reload retires the old net/http servers and a connection accepted at that moment can be closed before its request is read (measured in Revision 9: about 0.6 to 0.9 new connections per reload, on the panel and on every app). That broke the promise that deploying one app costs other apps and the panel nothing. Alternatives checked against Caddy v2.11.9: dynamic_upstreams (a 5-minute global goroutine that never stops, reverseproxy/hosts.go:166-177, per-request provisioning, and static pages still need a matcher), a listener wrapper (the retiring server closes the accepted connection, so it cannot fix the drop), and moving apps or the panel out of Caddy (against ADRs 0004 and 0010).

Decision.

  • A small handler module, http.handlers.serverdock_app (internal/agent/proxy/app.go), reads one package-level atomic.Pointer to an immutable table keyed by the local port of http.LocalAddrContextKey, loaded once per request. A static entry (the "not running" and maintenance pages) is written by the handler and never reaches reverse_proxy; an upstream entry sets the request variable sd_upstream and calls next; unknown port or no table is the "not running" page. It never calls next without setting the variable.
  • One reverse_proxy for all apps, with a static upstream {http.vars.sd_upstream} (placeholders are replaced per request, reverseproxy/hosts.go:117), network_proxy: none, and none of: passive health checks, max_requests, retries, dynamic_upstreams. The one host entry is shared by every app, so a failing app must never mark it down.
  • All public ports are listeners of one Caddy server. The Caddy config depends only on the set of ports; the table carries everything else. Applier.Apply loads (with bind isolation, a failed port leaves the listen list) only when the port set changes or a retry of failed ports is asked (proxy_apply.retry_failed, set by the control plane for an explicit retry while a port is failed). Otherwise it swaps the table and calls no caddy.Load, even while another service's port is taken. The table is stored after every successful load, so table and running config never diverge.
  • proxy_apply validates upstreams against the recorded meta.app_subnet (no Docker call), so a switch works while Docker is hung.

Consequences.

  • One custom Caddy module (about 100 lines) to maintain and re-test on every Caddy upgrade (TestClientCannotInjectUpstream, TestReverseProxyWithoutTheVarFailsClosed, TestHandlerUnderConcurrentSwaps, TestOneTickerForAllAppRoutes and the 20-switch integration test run on every bump). It depends on http.LocalAddrContextKey, request vars and upstream placeholders.
  • The table is package-global: exactly one Applier may write it per process (server mode); the remote agent never builds one with apps, and its config is unchanged (golden test).
  • The upstream-health metrics ticker is now exactly one 10 s ticker once at least one public port exists (it was one per upstream route), not rebuilt on a switch; it is rebuilt only by a reload.
  • A deploy, rollback, redeploy or restart of one app reloads nothing and drops no request on other apps or the panel. Adding, changing or clearing a public port, deleting an exposed service, the first sync at boot, "Try again" for a failed port and bind isolation still reload, and keep the Revision 9 behaviour (a connection being opened at that moment can be closed before its request is read; open streams are closed within 10 s). Step 15 measures them.
  • A resync after a Docker events reconnect (plan 0004 step 10) never asks for the retry of failed ports (retry_failed false): it reloads nothing because a port is taken, and the route lists it sends are table swaps. Only the first resync after a start (the "first sync at boot" above) and "Try again" retry.
  • Between a load and the table store, a newly added port answers "not running".
  • M4 can key the same handler by Host (domain routing) instead of the local port.

Addendum B — Domains and certificates without on-demand TLS

Status: accepted by the maintainer (2026-12-02, at the plan 0006 step 1 gate, conditional on Revision 5, which this commit adds).

Implementation status (2026-12-02, plan 0006 step 14): implemented in M4a on branch m4a (PR #35, merge pending); it stays accepted. What the build confirmed and what it added to the decision, in one place:

  • D1, D2, D3 and D12 hold as written (V2, V5, V6, V7, V11, V15 in plan 0006 Revision 4; the Pebble suite of step 11 on the pinned images).
  • The event subscription in Provision is built as decided (TestEventSubscribedOnceDeliveredOnce, -race). The upgrade checklist in architecture.md says when it must be re-checked.
  • Three things the implementation needed beyond the text above: (1) a catch-all automation policy (no subjects, the manager, an explicit issuer), kept once any name was tried in the process, because a managed name that matches no policy falls to Caddy's default public issuer and certmagic really contacted Let's Encrypt for it (TestALeftoverManagedNameIsNeverRenewedOrSentToACA); (2) a restore load after a failed caddy.Load, because the failed load leaves certmagic's shared cache options bound to the discarded tls app, so certificate events are dropped until the next good load (measured with the internal issuer; behaviour with ACME is not measured, and that renewals run under the discarded app's configuration is a reading of the source, not a measurement) (TestCertEventsResumeAfterAFailedLoad); (3) an upload-wins connection policy (the uploaded names ask only for a tag no cached certificate has), because a straggling issuance could otherwise shadow an upload (TestStaleUploadIsNotResurrected).
  • For up to about 10 ms after a successful load the previous config can still answer a new connection (Caddy's app.stop); recorded as an accepted risk in security.md.
  • Three upstream reports are drafted and not posted (plan 0006 Revision 12).

Context. The Decision above says "on-demand TLS gated by our DB". M4a (plan 0006) adds app domains, a panel domain, automatic HTTPS and uploaded certificates. Step 1 checked the alternatives against Caddy v2.11.9, certmagic v0.25.6 and Pebble v2.10.1 (plan 0006 Revision 4). On-demand TLS puts an issuance decision on every TLS handshake from the public internet; ServerDock already knows every name it should serve, so that decision can be made once, from the database, at config time.

Decision.

  • D1. Names are listed explicitly. Each automatic domain goes into the tls app's certificates.automate list, generated from the database, with its own automation policy (explicit ACME issuer). Nothing is issued for a name an admin did not add. automation.on_demand.permission is a deny-all module (tls.permission.serverdock_deny), so no handshake can start an order. This replaces "on-demand TLS gated by our DB". Verified: a handshake for an unlisted name, a listed name with no upload and a subdomain of an uploaded name all get the panel leaf and make no ACME order (V11).
  • D2. One HTTPS server on :443 for the panel and every domain. The per-request answer comes from an in-memory table keyed by Host, swapped atomically, like Addendum A's port table. Public-port apps stay in their own plain-HTTP server, because Caddy applies a server's TLS connection policy to every listener of that server (V15). No server sets trusted_proxies.
  • D3. A route-table apply never triggers a caddy.Load. Only exposure changes (public ports, domains, the panel domain, ACME email) and the pause/resume jobs load. A failed load that includes the TLS/domain part is retried once with the last committed TLS/domain part, so working domains keep serving. caddy.Load does not wait for issuance, and a failing name never fails it (V5); a load restarts certmagic's attempts for every name that has no certificate (V6, V19).
  • D12. Uploaded certificates are served by a certificate-manager module (tls.get_certificate.serverdock) that reads one atomic.Pointer to an immutable in-memory map, filled through agent ops; the private key never enters the JSON config. A listed name with no entry gets the panel leaf, because a nil answer together with the deny permission fails the handshake (V11). Replacing a certificate is a pointer swap with no load (V11).
  • Events. Certificate outcomes (cert_obtained, cert_failed) reach the control plane through a plain Go handler, not a Caddy module. The deny permission (tls.permission.serverdock_deny) subscribes it with events.App.On in its own Provision, once per load, in server mode only. There is no apps.events in the config. Subscriptions in the config are applied in the events app's Start (caddyevents/app.go L146–150). That can run after the tls app has started certmagic goroutines, which read the same map without a lock: a data race found in step 1. Subscribing in the permission module is race-free because of source order. caddytls.TLS.Provision provisions the global permission (about tls.go L265–275) before the automation policies (L282 onward) create certmagic's configs. Before those configs exist, certmagic emits nothing. A module inside a policy has no such guarantee. Every Caddy upgrade re-checks this order.

Consequences.

  • Rule 12 of docs/security.md holds by construction: only listed names are ever sent to a CA.
  • A handshake for an uploaded name costs one map read; a managed name costs the certmagic cache lookup.
  • ServerDock owns four small Caddy modules (Addendum A's handler, the host table, the manager, the deny permission); all are re-tested on every Caddy upgrade (the manager and deny tests, a -race test of the event subscription, the -race reload test).
  • No generated string contains { or } except generator-owned placeholders (Caddy expands {file.*} and {env.*} in many fields).
  • pki only with install_trust: false; automatic_https disabled on every server.
  • Events are best effort; no security decision depends on an event arriving.
  • Caddy delivers no event for an attempt a later load cancelled.
  • pki and the internal issuer are linked already (no binary growth) but are loaded only with the hidden --tls-issuer internal, with install_trust: false; otherwise Caddy's local CA tries to install its root into the host trust store with sudo.
  • Switching a domain between automatic and uploaded is one load each way (V12).