ServerDock — Architecture
Draft 1, 2026-11-20. AI-written from research/03-architecture-options.md (on GitHub); not yet confirmed by the maintainer. Decisions are recorded in decisions/ (on GitHub) (0001–0007 accepted 2026-11-20).
Overview
flowchart LR
subgraph Clients
B[Browser SPA]
CLI[serverdock CLI]
MC[Claude Code / MCP clients]
end
subgraph CP["serverdock server — one Go binary"]
API[REST + WebSocket API · auth · RBAC]
MCP[MCP endpoint /mcp]
AI[AI assistant loop · BYO key]
REG[Action registry · typed ops · risk tiers · dry-run]
AUD[(Audit log · hash-chained)]
DB[(SQLite WAL · state · jobs · metrics rollups)]
HUB[Agent hub · mTLS · multiplexed streams]
LOC[In-process local agent]
end
subgraph Node["App server (1 GB VPS, NAT ok)"]
AG[serverdock agent · Go]
CAD[Embedded Caddy · ACME]
DK[(Docker Engine)]
APPS[User apps & DBs]
end
subgraph Builder["Builder server or CI (optional)"]
BA[agent · role=builder]
BK[BuildKit + Railpack]
RG[(Registry)]
end
B --> API
CLI --> API
MC --> MCP
API --> REG
MCP --> REG
AI --> REG
REG --> AUD
REG --> DB
REG --> HUB
REG --> LOC
AG -- outbound WSS --> HUB
BA -- outbound WSS --> HUB
AG --> DK --> APPS
CAD --> APPS
BK --> RG
AG -- pull --> RG
AI -. HTTPS .-> CL[(Claude API)]
Key decisions
Scroll sideways for more columns
| Area | Decision | Why |
|---|---|---|
| Language | Go for control plane, agent and CLI (ADR 0002) | Embeddable compose-go, BuildKit, Railpack, Caddy/certmagic; static cross-compile; infra contributor pool. Rust saves only ~5–10 MB. |
| Shape | One binary, modes server, agent, CLI. Single node runs the agent in-process. |
No separate DB/Redis/websocket containers — the biggest RAM win. |
| Database | SQLite (WAL), pure-Go driver, single writer + read pool; jobs table instead of Redis; optional Litestream to S3. Keep a storage interface for a future Postgres backend. | Few MB vs 30–80 MB for Postgres + Redis. Write volume is low. |
| Transport | Agent dials out over TLS (WebSocket), multiplexed streams (yamux). One-time enrollment token → Ed25519/mTLS identity. | Works behind NAT/CGNAT, no inbound ports, no SSH keys stored (ADR 0003). |
| Operations | Every agent RPC is a typed operation (ComposeUp{stack,rev}, ContainerRestart{id}), executed via the Docker API. Exec only with argv arrays, never sh -c. |
Removes the command-injection class behind most Coolify/Dokploy CVEs. |
| Proxy | Caddy embedded in the agent, configured with full JSON from desired state; certificates for explicitly listed names (the automate list, generated from our DB), with every on-demand path denied (ADR 0004 addendum B, Domains and HTTPS). Fallback: Caddy container via Unix-socket admin API. |
~20–40 MB vs Traefik ~80–120 MB; atomic reloads; no labels (ADR 0004). |
| Builds | Dockerfile, Compose, Railpack on BuildKit. Default: builder server or CI; local builds capped by cgroup. BuildKit runs only during builds. | Builds must never OOM a small app server. Nixpacks deprecated; CNB too heavy. |
| Metrics | Read cgroup v2 + /proc directly every 15 s; rollups in SQLite (15 s/24 h → 1 min/7 d → 10 min/30 d → 1 h/1 y). | docker stats polling caused Dokploy's CPU storms. |
| Logs | Docker local log driver with rotation as the source of truth; stream only while subscribed, always cancel; search with grep on the agent. |
No Loki; no orphaned docker logs processes. |
| Events | Subscribe to the Docker events API for state changes instead of polling. | Idle CPU ≈ 0. |
| Frontend | SvelteKit static SPA embedded with embed.FS; uPlot charts; xterm.js terminal; REST typed from OpenAPI + one WebSocket. English only. |
Small bundle, no server RAM cost (ADR 0005). |
| AI | One action registry shared by UI/REST/CLI/assistant/MCP. Risk tiers read / mutate / destructive; server-enforced approvals; secret redaction; Anthropic Go SDK; zero idle cost. |
AI can never exceed the caller's permissions. |
Core concepts (data model sketch)
- Server — a host running an agent (local or remote); roles:
app,builder,edge. - Project → Environment → Service (app from image/git, Compose stack, or database).
- Deploy — immutable record: source revision, built image digest, resolved env (encrypted), compose, routes, health result, actor. Rollback = redeploy an earlier Deploy.
- Domain — host name → service port, TLS state, diagnostics.
- Backup / BackupRun — schedule, target, result, restore-test result.
- Secret — encrypted value; reveal is an audited action.
- Action — registry entry: name, JSON schema, risk tier, required scope,
dryRun(),execute(). - AuditEntry — actor (user, token, AI session), action, args (redacted), dry-run, approver, result, prev-hash.
- Job — durable queued work with lock key (per service/server), attempts, cancellation.
Deploy flow (single node, git source)
- Webhook arrives → signature verified → Job queued (superseded jobs for the same service are cancelled).
- Clone into a sandbox dir (refuse symlinks escaping the repo) → build with Railpack/Dockerfile under cgroup caps, or hand off to a builder.
- Compose/service spec passes policy check (no
privileged, host pid/network, docker.sock or/mounts, devices — unless the admin allows it, audited). - Start the new container(s) beside the old ones → health gate (HTTP/TCP/command) with timeout.
- Healthy → switch Caddy upstream atomically → stop old containers after a drain period. Unhealthy → remove the candidate, keep the old version running, report with the log tail. As built for image deploys (M3a step 8b,
internal/deploy/switch.go): the switch is a route override applied as an in-memory table swap in the agent (no Caddy load, so no request is dropped on any app or the panel); the commit is one database transaction (services.active_deploy_id,deploys.committed_at, the stage rows) run as the mutate of the route lock's no-retry apply; then a bounded drain (drain_s), then the old container is stopped and removed. The old container is never stopped before the commit, on any path. Switch and commit run on a context cut off from the job (a cancel, a supersede or thetimeout_swatchdog cannot reach them): entering the switch is one write that checks the job's cancel flag, anddeploys.cancelanswers 409 from that moment. A failed switch or commit re-applies the database's routes on a fresh context and removes the candidate (kept, withapp_safeunknown, if the proxy does not confirm the repair). - Record Deploy, update commit status, notify.
Deploy flow for image sources (as built, M3a)
The git flow above is M5. M3a deploys a public image as one container per service (internal/deploy, plan 0004). The whole path:
- Request.
services.deploy(orredeploy,rollback,services.createwithdeploy:true) runs through the action registry as the caller. One transaction writes the deploy row (an immutable snapshot of the service's settings; no address yet) and a job row, and cancels the service's queued jobs as "superseded"; a running one is flagged. - Scheduler. One goroutine, at most two workers, one running job per lock key
service:<id>; it dispatches nothing until the reconciler's first resync has opened its start gate. It runs the job as the actor that queued it:SystemInvoker.InvokeAs(stored actor, "jobs.run_deploy")re-checks the policy now (a token revoked since, a user who is no longer the admin or whose credentials changed, is denied); the audit row carries that actor withexecutor = system. - Stages, each a row in
deploy_stagesand each an op to the local agent over the in-memory session (internal/agentops, op protocol v1, allLocalOnly):pull:image_pullwith a stall timeout and a free-space check, thenimage_inspectrecords the image id and digest (a redeploy or rollback uses the local image id, or pulls the recorded digest).check:policy.CheckImage, then the static address is allocated (under the allocation lock, from a fresh list of this install's containers plus the database) and the create body is built and passed throughpolicy.CheckCreate.start:container_create(the agent re-checks the exact bytes, sets the instance label itself) andcontainer_start; the runner confirms the address.health: the agent dials the container at its address (health_check) every second until the configured number of passes in a row, within the timeout. A supersede or cancel here counts as unhealthy.switch,commit,drain,stop_old: see Deploy strategies. The previous container is stopped only after the commit; switch and commit run on a context cut off from the job.
- Routes. Every change of what Caddy serves goes through one route lock and one
proxy_applyto the agent, which re-validates the whole list. The control plane emits an upstream only when its state map shows the service's own container, at the recorded address, running. - Reconciler. At start
ResolveInterruptedruns once and changes only the database: a committed deploy issucceeded, an uncommitted one isfailed (interrupted by restart). The reconciler's loop goroutine then runs from server start; it holds the Dockereventsop open (a second goroutine holds that call only while a connection lasts). On every (re)connect the order is: open the stream, list this install's containers and inspect them, settle in the database (finish a deploy whose unknown commit outcome did commit, raiseapp_safe), apply the routes, re-inspect the container ids that had events during the list, open the scheduler's gate, and only then remove orphans and start a stopped live container. After akill -9or a daemon restart the same rules bring the app back: a committed deploy is finished (its old container removed), an uncommitted one has its containers removed. ADR 0012, decision 7. - Record. The deploy row ends
succeeded,failed,cancelledorsupersededwith a reason code andapp_safe(did the previous version keep serving); the container's log tail is kept as a gzip file (last 10 per service); one outcome audit row is written for the job's intent.
The browser reads state through services.* and deploys.* actions (polled every 2 s only while a deploy page is visible); nothing is pushed.
App network and static addresses (M3a)
- One bridge network per install,
serverdock-<install id[:8]>, labelled with the install id, IPv4, created with an explicit subnet: the first free/24of10.250.0.0/16that overlaps no Docker network, host interface or route, or--app-subnet(a/24to/20in RFC 1918 space or in 100.64.0.0/10, the CGNAT range Tailscale uses) at first start. The subnet is recorded inmeta.app_subnetand not changed afterwards; a later overlap refuses new deploys with an honest reason and leaves running apps alone.enable_icc=false: containers cannot talk to each other directly, only through the host. - The gateway is
.1, and the top quarter of the subnet is Docker's dynamic range (IPRange), so a container attached by hand never takes an address ServerDock allocates. Each deploy gets a static IPv4 from the rest (a/24gives.2to.191), allocated at thecheckstage, never reused while any container of this install still holds it, recorded indeploys.ip, and set at create. A container keeps its address across container and daemon restarts, so an upstream never points at another service's container. - Nothing is published on the host. Caddy dials the container's address; the only entry points are the public ports Caddy listens on. ServerDock must run on the host or with host networking to reach the app network (QM3a-7). On Docker before 28, hosts on the same LAN may be able to reach these addresses (accepted risk N13, security.md).
- At most 100 services per install and about 105 addresses in use at once.
Project networks and service DNS (M3b)
Each project has one more bridge network, serverdock-<install id[:8]>-p<project id>, labelled with the install id and the project id and created internal (no egress, no NAT, no route outside) with its own /25 (125 addresses). The /25 is chosen once, the first time a project deploys: the first free /25 of 10.250.0.0/16 (or of --project-pool, a /16 to /25 in private space) that overlaps no Docker network, host interface or route, the app network or another project; it is recorded in projects.subnet and never changed afterwards. A later overlap (a VPN added since) refuses the deploys of that project only; running apps are unaffected. When no /25 is free, only the project that needs one is refused, with "no free address range for project shop's network in 10.250.0.0/16; free one, or start ServerDock with --project-pool".
- A container joins at create with one alias, its service name, so the services of a project reach each other by name (
http://api:8080) on any port, and a candidate can reach its peers by name during its own health gate (an app that connects to its database at start passes the gate). Containers stay on the app network too (Caddy reaches them there, at their static address). Docker also registers the container's name (sd-<project>-<service>-d<deploy>-a<attempt>), which tells nothing beyond the service name. No--dns-searchor--dns-optionis set: Docker's resolver answers the bare service name on glibc and on musl images, also on a host with a search domain (measured, plan 0005 step 2 and the integration testTestServicesResolveEachOtherByName). - Blue-green and the name. Docker cannot add an alias to an existing endpoint, and a candidate that joins only after its gate could not reach its peers while it is checked. So the candidate has the name from its start: from the moment the new version starts until the old one stops, the service name resolves to both versions' addresses (Docker's DNS returns both, in varying order), so a peer may reach the new version before its health gate has passed. An unhealthy candidate is removed within
health_timeout_sand its name goes with it. Stop-first services never overlap, and a writable volume makes a service stop-first, so a database never has two versions answering. - Isolation. A container is on its project's network and the app network (
enable_icc=false), so with Docker's firewall rules on, services of different projects cannot resolve or reach each other. Public ports and host listeners stay reachable as before (accepted risk B10). A host firewall rule that names a bridge (for example the app network's) does not cover the per-project bridges: if you filter container traffic by interface name, add the project bridges (docker network ls --filter label=serverdock.instance=<id>). - Failures are create failures. The check stage ensures the network (
project_network_ensure: idempotent, refuses a foreign network, another range, a non-internal one, a gateway mode that is notnator an option ServerDock does not set). If the agent finds the network gone at create (it inspects it first, so a missing image is never mistaken for it), the runner ensures it again once and creates once more. Any other refusal isstart_failed: blue-green removes the candidate and the old version keeps serving; stop-first starts the old container again (a stopped container keeps its network endpoints). No stage is added, so the boot pass has no new rule. - Upgrade from M3a. A running service has no project endpoint until its next deploy; nothing about it changes before that.
- Removal. A project's network is removed only after its row was deleted (decided inside the same transaction that deletes its last service), after the commit, never forced, and never while any container labelled with the project exists, in any state. A network that cannot be removed is left in place and logged. The full resync also removes an orphan: a network of this install, named and labelled exactly as above, whose project has no row (
reconciler.remove_network, security.md). Someone can stilldocker network rmthe network of a project whose containers are all stopped (Docker refuses only while endpoints are active); those containers then cannot start, even if the network is made again, and a stop-first restore endsprevious_version_downuntil the next deploy. - Locks. The order is project, then service, then allocator, then route (
internal/deploy/locks.go, checked by thetesthooksbuild). A deploy holds its project's lock shared from the start of its job until its container is created. A service delete holds no project lock while it works (a slow volume removal never holds up a sibling's deploy): after its rows are gone and its service lock is let go, it takes the project's lock exclusively to remove the network, so a deploy that is between its network ensure and its create is waited for.reconciler.remove_networktakes no lock of its own: only the resync calls it, the resync takes the project's lock withTryLockand skips a busy project, and the action re-checks that the project row is absent (ids are never reused). A create can therefore never land between the agent's container check and its delete.
Gateway mode recovery
ServerDock refuses a network (the app network, or a project's network) whose com.docker.network.bridge.gateway_mode_ipv4 (or _ipv6, when the network has IPv6 on) is anything other than unset or nat. nat-unprotected lets hosts on the LAN reach a container's unpublished ports directly. New deploys are refused and the Overview shows the reason with a link here. Fixing it means app downtime: the network cannot be changed in place, so its containers are removed and it is created again. Named volumes are kept by docker rm -f (only anonymous volumes and docker rm -v remove data), but each service is down until it is redeployed.
- If the Docker daemon sets a default for new networks, remove the gateway-mode entry from
default-network-optsin/etc/docker/daemon.jsonand restart Docker. Otherwise the network is created wrong again. (On Docker 28 and later ServerDock setsnatitself when it creates a network, but not on a network that already exists.) - Stop ServerDock.
- Remove the install's containers:
docker rm -f $(docker ps -aq --filter "label=serverdock.instance=<instance id>"). Quote the id as shown; it is the value of theserverdock.instancelabel (docker inspectany ServerDock container to read it). - Remove the network:
docker network rm "<network name>". The name is in the Overview reason:serverdock-<first 8 characters of the instance id>for the app network, with-p<project id>added for a project network. For a project network only the project's containers (labelserverdock.project) need to go. - Start ServerDock. It creates the network again with the recorded subnet.
- Redeploy each service.
Until step 3, running apps keep serving, and they stay exposed as long as the network is in this state.
Network option recovery
ServerDock checks the driver options of the app network and of each project network. Only these are allowed: the gateway modes (unset or nat), enable_icc, enable_ipv4, enable_ipv6 and com.docker.network.driver.mtu (an integer from 68 to 65535). Any other option, for example com.docker.network.bridge.trusted_host_interfaces, host_binding_ipv4 or enable_ip_masquerade, changes who can reach the network or the host, so the network is refused. New deploys are refused and the Overview shows the reason with a link here. Apps that are already running on that network keep running, and they stay exposed as long as it is in this state.
The usual cause is a default-network-opts entry in /etc/docker/daemon.json, which Docker adds to every network it creates.
- A network ServerDock has just created (a fresh install, or a new project) is removed again by ServerDock when it finds the option. Remove the entry from
default-network-optsin/etc/docker/daemon.json, restart Docker, and deploy again. That is all. Removal is best effort: if the network is still there, follow the steps for an existing network below. - A network that already existed is never changed or removed by ServerDock. Fixing it means app downtime, because the option cannot be removed in place:
- Remove the entry from
default-network-optsin/etc/docker/daemon.json(or stop creating the network by hand with that option) and restart Docker. - Stop ServerDock.
- Stop and remove the apps on that network:
docker rm -f $(docker ps -aq --filter "label=serverdock.instance=<instance id>")for the app network, or add--filter "label=serverdock.project=<project id>"for one project's network. Named volumes are kept bydocker rm -f. - Remove the network:
docker network rm "<network name>". The name is in the Overview reason (serverdock-<first 8 characters of the instance id>, with-p<project id>for a project network). - Start ServerDock. It creates the network again.
- Redeploy each service.
- Remove the entry from
Volumes and bind mounts (M3b)
A service's storage is a list of at most 10 mounts (services.set_volumes, admin scope, fresh two-factor confirmation, no tokens). The list is saved as rows; a deploy records the list in its snapshot when it is queued, so a later change applies at the next deploy and never changes a queued one.
- Named volumes are Docker
localvolumes namedsd-<install id[:8]>-s<service id>-<name>, with ServerDock's three labels and no driver options. They are made (volume_ensure) at the check stage, under the service's lock, and never removed by a deploy. A volume that is taken off the list is detached: its row stays withdetached_atset and its data stays; adding the same name again reattaches it. - A writable mount makes the deploy stop-first (two containers must never write to one volume): the maintenance page goes up, the old version stops, the new one starts. A candidate that is interrupted still has at most 10 s to stop, so a stateful app that needs longer is killed (plan a migration accordingly). Read-only mounts keep blue-green.
- A volume of the right name that is not ServerDock's (no labels, another driver or options, another service's) is never adopted: the deploy fails with the volume's name and says to remove it by hand (
docker volume rm <name>) or to give the volume another name. - Deleting a service keeps its volumes unless
delete_volumesis set, and the question is asked again at each delete. Volumes (detached ones too) are removed after the containers and before the rows; a volume that a container still uses is kept and the delete finishes; a timeout from Docker means the outcome is unknown (it is asked again, and a second timeout fails the delete so it can be run again). Bind host directories are never deleted. Volumes are not backed up (database backups come with M6; early use is for data that is disposable or backed up elsewhere).
Bind mounts and --bind-root
Bind mounts are off until the operator names host directories with --bind-root DIR (repeatable; Linux hosts only: the POSIX ACL check reads an extended attribute that exists on Linux). A service may bind-mount only a directory inside a root. The server refuses to start when a root:
- is not an existing directory, is equal to, above or inside a denied path (
/, ServerDock's data directory, the directories of the Docker, control and debug sockets, Docker's data root,/var/lib/containerd,/run,/proc,/sys,/dev,/boot,/etc,/usr, the system library directories,/root, the directory of the ServerDock binary), or is nested in another root (the pair is named); - or ServerDock itself runs in a container (the paths it sees are not the host's).
How to prepare a root:
- Put it on its own
nosuid,nodevmount. A container with a writable bind can leave a setuid file or, withCAP_MKNOD(a default capability), a device node in its directory; Docker appliesnosuidandnodevto a bind only as the filesystem's mount has them. ServerDock reads/proc/self/mountinfoat start and warns for each root that is not on such a mount (it does not refuse: that would keep bind mounts off on most hosts). chmod o-rwxthe root and every source. Neither may have any permission bit for "other" users; each ancestor up to/may not be writable by "other" users. All of them must be owned by root or by ServerDock's user, and may not be group-writable unless the group is root's or ServerDock's own. A source may not be a root itself: use a directory inside it, so a directory the container cannotchmodalways lies between host users and the contents.- ServerDock's group must be private to it. The rules accept a directory that ServerDock's group may write, so every member of that group can write there. ServerDock warns at start when
/etc/grouplists other members of that group, or members of root's group (gid 0) other than root: the rules trust group 0 like root. - No POSIX ACLs on a root, a source or an ancestor (the mode bits cannot show what an ACL grants).
- Use local filesystems. The rules read modes, owners and attributes of every ancestor, and
EvalSymlinksruns at save and at each deploy; on a network filesystem those calls can be slow or hang. ServerDock does the filesystem work outside its database write transaction, but a root should still be on a local disk.
Rules at save, at the check stage and again in the agent just before the container is created: a source must be its own real path. A path that is a link, or resolves to another directory than it spells, is refused at save and at the check stage, and the agent refuses it too instead of mounting something else: what is recorded is what Docker mounts, so the overlap rule never judges a name that can be pointed elsewhere. The source is an absolute, canonical, printable path with no .., , or :; after resolution it is an existing directory under a root and not under a denied path. No two bind sources may overlap, in any service, the same service included (equal, one above the other): the rule is checked against every other service's list, every queued, running and live deploy, and the deploys of every container of this install in any state (a stopped candidate or old version kept for the resync too). A service's own other deploys may name the same path (a redeploy mounts the directory it already mounts), but not a path above or below it. A rollback runs the check stage again.
Swapping the image of a service that has a bind mount (services.set_source, a new tag through services.update or services.deploy with an image_ref, a rollback to a deploy of another repository) needs a signed-in session with fresh two-factor confirmation and denies every API token and MCP client (QM3b-11): a different image is the easiest way to read what the bind exposes. A service with only named volumes, or none, is unaffected.
What this does not close. Docker mounts a bind by path at every start of the container, so a directory that is swapped for a symlink after the agent's resolution is followed at the next start (a restart included). The actors who could swap it are a container with a writable bind covering that path (the overlap rule removes that) and a host user who can write inside the bind root (the owner and mode rules). On kernels before 5.12 read_only is not recursive for a bind: a submount inside a source stays writable. Both are in security.md.
Environment variables, secrets and registry credentials (M3b)
- Env versions. A service's variables are a list of immutable versions (
service_env_versions): one secretbox ciphertext of the whole list (a name, a value and a secret flag each; sealed underDATA/keys/master.keywith the AADservice_env_versions/<service id>/v<version>, so a ciphertext cannot be moved to another service or version), anames_jsoncolumn for display only, and the actor. A version is never updated (a trigger refuses it).services.env_settakes the version number it was based on (base_version; a different current version is a 409) and either writes nothing (the same set), points the service back at the live deploy's version (the same set as live), or seals a new version; 20 versions are kept besides the live one, older ones are pruned when a version is written. Rollback limit: after more than 20 env changes the older deploys can no longer be rolled back to, and a rollback to one is refused with a clear 409 ("the variables that deploy #N ran with were removed ... deploy with the current variables instead",deployactions.go). The UI does not disable those history entries: the dialog's warnings (lib/rollback.ts) cover a differing or unreadable variable set, and the refusal shows as the server's message in the alert. A secret entry can be kept unchanged (keep, which needssecret: true);env_getreturns plain values only,env_revealone secret (fresh two-factor, no token or MCP). - A deploy records the version it was queued with (the snapshot, frozen in the enqueue transaction with the mounts and limits), so a change applies at the next deploy and a rollback restores the target's env version (a
writetoken may only roll back to a deploy that ran the current version). The runner decrypts the version at the check stage (once for the container, once for the redactor; nothing is cached) and four context variables are appended to the user's (SD_DEPLOY_ID,SD_ENV,SD_FQDN,SD_COMMIT; the last two empty until M4a and M5). Docker holds the environment in clear: ServerDock's ops never returnEnv, but anyone with Docker access can read it (security.md). - The redactor (
internal/redact,redact.ForSecrets): from the secret values of a deploy's version, the service's current version and the registry password for the image's host, it builds a set of forms (the value, each line of 8 bytes or more, the cleaned form, the JSON-escaped form, the%qform) and an exact-match scanner. It is applied (1) to every deploy reason, stage detail, job error and agent message before they are cut to 512 or 256 bytes, (2) when a container's log tail is kept, as a stream that holds back the longest form minus one byte, and (3) on everydeploys.logread. It fails closed: if the secrets cannot be read, a log is not kept, a read answers 503, and a reason falls back to a fixed text. It cannot catch another encoding of a secret or a secret the app generates. The cost is transient and per request (about 5 MiB of heap for ordinary text, up to about 11.3 MiB for a log of lone invalid bytes (each becomes three bytes), and at most about 23 MiB with the two-read cap, all transient (TestDeployLogReadPeak, plan 0005 Revision 11)), with no cache and no goroutine. - Registry credentials (
registries): one row per exact host key (Docker Hub's three names aredocker.io), the password sealed with the AADregistries/<host>/secret. For each pull the control plane resolves the host, checks every address (private needs the row'sallow_private, loopback needs--allow-loopback-registry, link-local and metadata always refused), and buildsX-Registry-Authfor that host only; the agent also requires the header'sserveraddressto equal the reference's host. There is nodocker loginand nothing is kept in the daemon's config. - Engine checks. The host's memory and CPUs (from the same events-connect read as the engine version, in Deploy strategies) bound
services.set_resourcesat save and again at the check stage; a limit with no readable totals fails closed.
Deploy strategies
- Blue-green (default for stateless): start beside, health gate, switch, drain connections, graceful stop timeout.
- Stop-first (chosen automatically when a writable volume is attached, e.g. databases, SQLite apps, uploads; M3b, see Volumes and bind mounts): show a maintenance page, stop old, start new, health gate; on failure restart the old one. Never two writers on one volume.
- As built in M3a (image sources):
- Blue-green is the default. The switch is a table swap in the agent, not a Caddy reload: the
serverdock_apphandler looks the request's local port up in an immutable in-memory table, and the onereverse_proxydials the address the handler set. A switch, a revert, a rollback, a restart and the maintenance page therefore never reload the proxy. A switch drops no request on other apps or the panel, and none on the deployed app for requests that finish withindrain_s(integration tests: zero non-2xx, zero dropped connections, zero retries, zeroloadcalls). A restart is an outage by design (the container is restarted in place), and the stop-first gap answers 503 with the maintenance page. The commit (services.active_deploy_id) is one database transaction run as the route lock's mutate. The drain waitsdrain_s(default 10, at least 10, at most 300) before the old container is stopped with its grace and removed. - Stop-first is explicit in M3a (a per-service setting); since M3b it is also chosen automatically for a writable volume or bind (see Volumes and bind mounts). Inside a gap of about
stop_grace_splus the new version's start and health gate, the route serves a 503 maintenance page withRetry-After; any failure or cancel after the old version stopped starts it again and gates it (app_safeyes, or no and ◆ Needs attention if it does not come back). - Two versions never run at once, also after a crash: in a stop-first gap the reconciler removes the candidate before it starts the old version again (the removal's grace is capped at 10 s), and a service whose kept candidate could not be settled is flagged
versions_keptso a restart or another stop-first deploy is refused until it is. - Only a reload of the proxy (adding, changing or clearing a public port, deleting an exposed service, the first apply at boot, "Try again" for a failed port, and bind isolation: k taken ports cost k + 1 loads, and one-by-one probing happens only when a load error names no port) can drop a not-yet-processed connection; see Background work and research 05 (on GitHub).
- No persistent volumes in M3a (M3b adds them). An image's
VOLUMEis anonymous and is removed with its container; only the named volumes and binds of M3b outlive a container. The stop grace of an interrupted stop-first candidate is capped at 10 s, so a stateful candidate is SIGKILLed after that (an M3b note for migrations). - Not built: the release phase, pre/post-deploy commands, and a post-switch monitoring window (alerts are M8).
- Blue-green is the default. The switch is a table swap in the agent, not a Caddy reload: the
- Release phase (optional): a one-off container on the new image runs migrations before either strategy; failure aborts the deploy.
- Logs of the last N deploys are kept as compressed files on the agent (disk-capped) so removing an old container never loses its logs.
Domains and HTTPS (M4a)
Plan 0006 (ADR 0004 addendum B). Domains are service settings in the database; the control plane generates the proxy's whole config from them, and the proxy never asks the database during a handshake.
The proxy shape
:80 server "main" [serverdock_http] (Caddy answers ACME HTTP-01 first; no reverse_proxy)
probe path -> HMAC of the nonce and host; other /.well-known/serverdock/* -> 404
panel hosts (non-loopback IP literals, --panel-host): while trusted for redirects -> 308 to the panel domain; else 308 to https://<host> (M2)
panel domain: trusted -> 308, else 503 "not ready"; app domain: certificate present -> 308, else a "being set up" 503
anything else -> 421
:443 server "https" TLS: managed (certmagic cache) -> manager (uploaded names; the panel leaf when a listed name has none) -> panel leaf (default and fallback SNI)
route 0 [serverdock_panel]: HSTS on the panel domain only, the IP -> domain redirect
route A: panel hosts -> reverse_proxy -> control socket (the sign-in refusal runs in the control plane)
route B: any other host (only when an app domain exists) -> serverdock_app (host mode) -> reverse_proxy {http.vars.sd_upstream}
:<port> server "apps" (M3a, unchanged: plain HTTP public ports)
tls app: load_files [panel leaf]; automate [names, not paused]; policies: production, staging, the manager policy for uploaded names,
and a catch-all (no subjects, the manager, an explicit issuer) that stays once any name was tried;
automation.on_demand.permission = serverdock_deny (global deny-all); disable_ocsp_stapling; disable_storage_clean
events: no events app in the config; serverdock_deny's Provision subscribes cert_obtained and cert_failed (server mode only, once per load)
With no domain the :443 routes are the one reverse_proxy to the control socket, byte for byte as before M4a, and the control plane answers 421 itself. When any domain exists, an unknown Host is answered 421 by Caddy and never reaches the control plane; only route A does. No server sets trusted_proxies. A remote agent's config is unchanged (TestAgentBuildConfigGolden). An uploaded certificate is served from an in-memory map by a certificate-manager module (tls.get_certificate.serverdock), and a connection policy that matches the uploaded names and asks only for a tag no cached certificate has makes the upload always win; the key never enters the JSON config.
What reloads the proxy
Invariant: no route-table apply ever triggers a Caddy config load. The applier keeps a config hash and a table hash. It always swaps the table and loads only when the config hash differs from the last attempted one; a failed hash is not retried by a deploy (it is shown in Needs attention until a new config loads or the admin presses Try again). The config hash holds only admin-controlled inputs and the applied pause flags, never a certificate event, the clock or a deploy.
Scroll sideways for more columns
| Change | Proxy effect |
|---|---|
| Deploy switch, rollback, redeploy, restart, maintenance page, "not running", resync | table swap, no load |
| Certificate obtained, renewed, failed or expired | nothing (trust is read per request) |
paused_until passing |
nothing by itself: the resume job loads (the domains.resume_acme row below) |
| Uploading or replacing a certificate for a domain that already uses an upload | certificate-map swap, no load |
| Moving a domain to another service; the keep-IP switch | table swap, no load |
| Adding or removing a domain; switching a domain between automatic and uploaded; test certificates on | one load |
| Test certificates off (test to production) | two loads (first without the name, so certmagic evicts the staging certificate, then with the production policy) |
domains.pause_acme, domains.resume_acme, "Try again now" on a paused name |
one load each (none if the hash does not change) |
| Setting, changing or clearing the panel domain; changing the ACME e-mail; a changed ACME directory | one load |
| Adding, changing or clearing a public port | one load (M3a; bind isolation retries are loads too) |
| A restore load after a failed load that left certmagic bound to the rejected configuration | one load, in the same call as the failure, at most once per failure (so a route-table apply still never loads) |
Every load restarts certmagic's attempts for each failing automatic name, which costs up to 2 failed validations per name; the restart budget (before every load, in the same transaction that records it) pauses a name with 2 restarts in the window in that very load, so the bound is at most 4 failed validations per name per hour with Let's Encrypt production without any event. D10a names two exceptions outside it: retries against a custom --acme-directory (no staging, every retry counts) and production tried straight after a staging success (up to 8 in an hour). The budget runs once per proxy_apply, before its first load, and Loads - 1 extra restarts are recorded afterwards. Accepted edge: a call whose context ends can make 3 loads (the attempt, one bind-isolation retry, the restore) while the control plane records a worst case of 2 restarts on an error. A load that includes the TLS and domain part and fails is retried once with the last committed part (D3's fallback), so a bad domain change never takes working HTTPS sites or public-port apps down.
Storage and backup
DATA/caddy holds the ACME account key, every managed certificate and its private key unsealed, locks, and, with the hidden --tls-issuer internal, the pki root key. It is in datadir.SecretPaths; every directory is 0700 and every file outside locks/ is 0600 (certmagic writes locks/*.lock 0644, in a 0700 directory, holding no secret). Uploaded private keys are not in it: they are sealed in the database (domain_certificates, AAD bound to the domain name) and put into the agent's memory only. The state backup (plan 0010) puts DATA/caddy inside its encrypted part and restores it with the database: a restore without DATA/caddy re-issues every certificate at the next start, which counts against Let's Encrypt's 50 certificates per registered domain per week and makes the mass-issuance peak. doctor --bundle (plan 0009) excludes it.
Caddy upgrade checklist
Run at every bump of Caddy or certmagic (module paths and versions are pinned in go.mod):
- Provisioning order. Re-read
modules/caddytls/tls.goProvision: the global on-demand permission module must still be provisioned before the automation policies create theirmagicconfigs (this is what makes the Provision-time event subscription inserverdock_denyrace-free, D7). Re-run the subscription test under-race:TestEventSubscribedOnceDeliveredOnce(needs Pebble;spike/m4a/README.md). If the order changed, the subscription is unsafe: take D7's no-events escape hatch. - The catch-all automation policy. Re-check that a policy with no subjects, the serverdock manager and an explicit issuer still prevents Caddy's default public policy for a name that matches no listed subject (
getAutomationPolicyForNameintls.go), by re-runningTestALeftoverManagedNameIsNeverRenewedOrSentToACA(real Caddy). - The restore load. A failed
caddy.Loadleaves certmagic's shared cache options bound to the discarded tls app (tls.goL218-224,caddy.goL435 and L505-513,Cleanupattls.goL531 in v2.11.9). Measured with the internal issuer (a standalone Caddy): 0cert_obtainedevents in 15 s after the failed load against 2 before it, while the certificate file was still rewritten; behaviour with an ACME issuer is not measured, and "renewals run under the discarded app's configuration" is a reading of the source, not a measurement. ServerDock works around the dropped events with a restore load, made in the same call as the failure (also when the caller's context has ended: the load calls take no context). Check whether it is still needed (TestCertEventsResumeAfterAFailedLoadwith the restore removed), and whether an upstream fix has landed. - The lag. Re-run
TestLagAtFiftyFailingNames(SD_PEBBLE_MEASURE=1) when certmagic's ACME limiter or Caddy's version changes;TestCertmagicACMERateLimiterIsStillTenPerTenSecondspins the limiter (10 events per 10 s). The restart window W = 70 minutes holds while the last validation after a load comes within 10 minutes at the 200-name cap. - Also:
TestNoTrustedProxiesInAnyServerWithDomains,TestGeneratorInvariants(noinstall_trust, noautomatic_https),TestInternalIssuerNeverInstallsTrust, the real-Caddy goldens, and a goroutine dump with 0, 1 and 2 failing names against the Background work rows.
Runtime compatibility
- Negotiate the Docker API version; publish the supported Docker range; warn when the host's Docker version changes; Docker release candidates run in CI.
- Engine version and host facts (M3b). On every successful events (re)connect the control plane reads Docker's
/versionand/infoonce (dockerapi.Client.Facts; a failed read is logged and never fails the resync) and keeps the engine and API version, the host's memory and CPUs and Docker's data root in memory. The one stored value ismeta.docker_engine_version, the version an admin last acknowledged, recorded silently on the first run. A different engine shows as "changed" insystem.docker(and so on the Overview) until an admin acknowledges that exact version withsystem.docker_ack. An engine older than 28.0.0 shows a standing warning and is logged once (N13); a version string that does not start with digits, a dot and digits makes no claim. A memory or CPU limit above the host's totals is refused when it is saved (services.set_resources) and again at each deploy's check stage. None of this has a timer. - Out-of-memory reports (M3b). The
oomaction is in the events filter the watcher already reads (nothing else was added to it). Anoomevent writesservices.last_oom_atfrom the reconciler's own loop, at most once per service per minute (an in-memory timestamp, dropped with the service), and a candidate that Docker restarts during its health gate fails with reasonoomonly if the stream saw anoomevent for that container. Docker clearsOOMKilledwhen it restarts a container, so the flag is never used to recover a missed event: an OOM during a gap in the events stream is missed. The Overview entry shows until the next successful deploy or for 24 hours, decided when it is read. - Docker RC in CI. The
integration-rcjob runs the integration tests against the newest Engine on Docker'stestapt channel (the runner's own engine removed, the apt key pinned by fingerprint). It is never a required check; the release checklist inCONTRIBUTING.mdsays where the maintainer reads it. First results (plan 0005 Revision 11): four runs on Docker 29.10.1 (replacing the runner's 29.4.2): three passed all suites (46796473234, 46800494069, 46815866109), and one (46807738439, at257865e) failed one M3a test,TestIntegrationTwentyReloadsUnderLoadCauseNoNon2xx(one request failed after its retry). It is not known whether that is the engine or a load flake. Deadline: settle it before Docker 29.10 reaches stable or before the M3b release tag, whichever comes first (owner: the maintainer, or the next milestone's orchestrator): run-run TestIntegrationTwentyReloadsUnderLoadCauseNoNon2xx -count=20on both the RC and the stable engine and log which hop failed.integration-rciscontinue-on-error, so a red nightly run notifies nobody; someone has to look. - Keep a container-runtime interface so rootless Docker / Podman can be added later (Phase 5).
- Build for the target server's architecture (amd64/arm64).
- IPv6 everywhere: proxy, networks, agent dial-out, DNS diagnostics.
Failure-handling rules
- Every long operation is a Job with a lock key, timeout and cancellation; restart-safe (resume or clean rollback on boot via reconciler).
- Downgrades are refused (a database with a newer schema), so apps stay offline until a binary that matches runs. M7b note: restoring an older database makes the reconciler's orphan rule remove live containers that the older database does not know; the restore flow must account for it.
- A reconciler compares desired state (DB) with actual state (Docker labels
serverdock.*) and reports drift; it only removes resources it owns (labelled by deploy attempt). - Agent disconnect: operations in flight are marked
unknownuntil the agent reports back; agent buffers metrics in a ring buffer. - Version skew: control plane supports agent N-1; agents self-update from the control plane, signature-checked.
Footprint budget
These are the budgets, measured by bench/run.sh in CI on a 1 vCPU / 1 GB VM (ADR 0008, ADR 0011). The two totals in bold have a hard ceiling (CI fails above it) and a tripwire (a warning: going above it needs a written reason in the PR and footprint agent review). Component rows are targets the bench reports but does not enforce. The remote-agent row becomes a gate when the slim agent ships in Phase 2. From M3a step 10 the gated scenario 2 is "S2 live watcher": the server runs with the host's Docker socket and its group, so the reconciler's events stream is connected during the idle window (bench/run.sh, the default). "S2 no Docker" (S2_DOCKER=0) is kept as a report-only comparison.
Transparent huge pages: on hosts with THP set to always (some RHEL-family images, Docker Desktop's VM) khugepaged collapses the Go heap into 2 MB pages and idle RSS rises in steps (measured +4.2 MB, or +1.6 MB with GODEBUG=disablethp=1; see plan 0003's idle-memory section). On madvise hosts, most VPSes, nothing changes. disablethp is a runtime-only setting (Go rejects it as a //go:debug default), so it is set through the environment: plan 0009 (M7a) adds Environment=GODEBUG=disablethp=1 to the systemd unit and the container image; operators can remove it.
Scroll sideways for more columns
| Component | Idle RSS | Idle CPU |
|---|---|---|
| Control plane (API, hub, scheduler, SQLite, SPA) | ≤ 40 MB | < 0.5% |
| In-process local agent | + ≤ 8 MB | — |
| Remote agent (slim build, Phase 2) | ≤ 20 MB | < 0.3% |
| Embedded Caddy | + ≤ 30 MB | — |
| Single node total | ceiling ≤ 200 MB · tripwire 80 MB | < 1% |
| Remote node total (agent + proxy) | ceiling ≤ 100 MB · tripwire 50 MB | < 0.5% |
| Binary size (server, compressed) | ≤ 40 MB | |
| SPA first load (gzip) | ≤ 250 KB JS |
Extra containers ServerDock adds to a managed server: zero (agent and proxy in one process), or one if the user chooses the Caddy-container fallback.
M3a adds to the single-node process (no new container): the events watcher (its loop goroutine from server start, plus a second goroutine and one Docker connection only while the events stream is connected), the scheduler (one parked goroutine, a timer only while a retry is waiting), and, once any service has a public port, one extra 10 s Caddy metrics ticker (see Background work). The release measurements (the CI "S2 live watcher" number against the 80 MB tripwire, S2 with one and with ten exposed services, RSS after a deploy, the full S4, the binary and the SPA) are in research 05 (on GitHub) and are PENDING until the CI bench run for the M3a pull request.
M3b adds no new timer, ticker, idle goroutine or cache (the one bounded wait it adds is inside a deploy job, see Background work) and no dependency; its work runs inside requests, jobs and the existing events (re)connect. Measured on the dispatched CI bench of phase-1-m3b at 257865e (run 46807738439): S2 live watcher 55.1 MB (M3a 54.0; planning number 58, tripwire 80), S4 46.7 MB (M3a 46.5; planning number 46.7, tripwire 50), binary 20.3 MB gzip, idle CPU 0.00 % and 0.01 %. On the final code (2d9ea43, run 46836498744): S2 55.0 MB and S4 48.1 MB (runs 47.2 to 48.2; read as run-to-run spread, see Revision 11's CI line), tripwires hold. The other scenarios (S5 to S7, S10, S11, the deploys.log peak) are local and informational, and two local criteria (S10 multi-layer HeapInuse, S11 RSS) were not met; see Revision 11: plan 0005 Revision 11 (on GitHub).
Control socket and local tools
The control plane listens only on a unix socket (--control-socket, default DATA/run/cp.sock, 0600 in a 0700 directory, at most 256 connections). The embedded Caddy is the only thing in front of it: it terminates TLS on --https-listen (default :443, the self-signed panel leaf DATA/pki/panel.pem) and answers :80 with redirects, and since M4a with ACME HTTP-01 challenges, the probe path and the "being set up" pages. The panel server speaks HTTP/1.1 and HTTP/2 only (protocols: [h1, h2], pinned by TestPanelConfig): there is no HTTP/3, so no UDP listener and no Alt-Svc: h3 header (TestNoTCPControlListener checks that the process holds no UDP socket on Linux). The tls app also sets disable_storage_clean. Before M4a this was because ServerDock managed no certificates through Caddy (the panel leaf is loaded from a file); since M4a it is on purpose the other way round: certmagic does manage certificates for the domains an admin added, and disable_storage_clean stops it from deleting stored certificates and keys of names that are removed or that a pause leaves out, so removing and re-adding a domain, or resuming a paused one, reuses what Let's Encrypt already issued instead of spending a new order (plan 0006 D19; those files stay on disk until M7b's housekeeping removes them). See Domains and HTTPS. Every route in the route table (internal/api/routes.go) declares its auth kind (public, setup-open, pending-2FA, session, session-or-token, debug socket), and only that kind's credential is read. Every request on it must carry exactly one X-Forwarded-For value holding one IP, which only our Caddy sets; anything else gets 400. A local tool that talks to it directly (M7a's doctor and any container healthcheck) therefore cannot use it like a plain HTTP port. A local tool that does talk to the control socket must send Host: 127.0.0.1 or Host: localhost (the Host allowlist answers 421 to anything else) and that one X-Forwarded-For. Local tools otherwise use the debug socket (--debug-socket) or read files and the database; they never need to forge a forwarded address.
Background work
Every goroutine that wakes on a timer, and the goroutines that exist per session. Anything that adds a timer adds a row (footprint checks this table). Lazy work (done inside a request or a handshake, with no timer and no goroutine) is listed so nobody adds a timer for it later.
Scroll sideways for more columns
| What | Where | Interval | When it runs |
|---|---|---|---|
| yamux keepalive, hub side | internal/hub/hub.go attach |
30 s | per remote agent session (off on the in-memory local pipe) |
| yamux keepalive, agent side | internal/agent/session.go ServeSession |
30 s | per remote session, in the agent process |
| Reconnect backoff | internal/agent/client.go sleepCtx |
1 s to 30 s, jittered | only while a remote agent is disconnected |
certmagic cache maintenance, (*certmagic.Cache).maintainAssets |
embedded Caddy (caddyhttp provisions the tls app) |
10 min renew check, 1 h OCSP tick (stapling is disabled but the tick stays) | running since M1, whenever the proxy runs: in server mode (S2) and in agent mode with --proxy-listen (S4). Seen in a goroutine dump (M2 step 3). The panel leaf adds no timer: it is renewed only at start (internal/pki, EnsurePanelLeaf). With app domains (M4a step 4) it has real work: the renew check for every managed certificate, and ARI (ACME renewal information) refreshes, which run from the same 10 min tick with no goroutine of their own and are paced by the CA (maintain.go, plan 0006 V10). |
certmagic per failing automatic name: doWithRetry (retry timer) and keepLockfileFresh (lock-file refresher) |
embedded Caddy, server mode with app or panel domains | doWithRetry waits on its retry timer (1, 2, 2, 5, 10 ... min, up to a day, for up to 30 days); keepLockfileFresh rewrites the name's lock file every 5 s |
only while a name has no certificate and keeps failing (and for a trusted name whose renewal keeps failing). Two goroutines per such name, at most 200 names (400 goroutines, about 1.6 MB of stacks, V10); fewer with D10a pauses. A written exception to the 15 s floor in plan 0002 rule 3: upstream code that cannot be configured, one small file write per tick, never for healthy names or with no domains. Plan 0006 step 11 measured idle CPU with 10 failing names at 0.07 % (2 ticks, against 0 to 1 for the baselines, far under the 0.5 % budget), so no Locker wrapper was added; it stays a possible item for the 0644 lock files. Agent mode runs none of it. |
Caddy pki app maintenance (maintenanceForCA) |
embedded Caddy, only with the hidden --tls-issuer internal (tests and the bench) |
a ticker loop | never in a normal install: the pki app is not in the config unless the internal issuer is selected (TestNoPKIAppUnlessInternalIssuer). |
Caddy's reverse-proxy upstream-health metrics updater, (*metricsUpstreamsHealthyUpdater).init (modules/caddyhttp/reverseproxy/metrics.go, Caddy v2.11.9) |
embedded Caddy, one goroutine per provisioned reverse_proxy handler (the panel's in server mode, the agent's routes in agent --proxy-listen) |
10 s ticker | running since M1 whenever the proxy runs, in S2 and in S4. Found in the idle goroutine dump at M2 step 14 (bench/results/2026-11-21-s2-idle-goroutines.txt). Caddy starts it unconditionally (it is not tied to the metrics config); it only sets a Prometheus gauge from in-memory health state, no I/O. Not removable by configuration. App routes (M3a step 6b, Revision 11) and app domains (M4a step 4): a written exception to the 15 s floor in plan 0002 rule 3: one extra 10 s Caddy metrics ticker once at least one public port exists, and one more once at least one app domain exists (the host-mode reverse_proxy of the HTTPS server; plan 0006 V15), not rebuilt on a switch (it is torn down and recreated only by a reload, that is a port-set or domain-set change; with no public port there is no app server and no port ticker; with no app domain there is no route B and no domain ticker). All app ports share one Caddy server and one reverse_proxy handler, and all app domains share one more (the serverdock_app handler in front of each answers static pages and picks the upstream from an in-memory table), in-memory gauge only (TestOneTickerForAllAppRoutes, TestAppTickerCountsPerState: 1, 2 or 3 tickers in all). A panel domain alone adds none. The idle-CPU budget is claimed only for S2 with no exposed service; with exposed services there is one more 10 s tick, however many services (measured in M3a step 15). |
Job scheduler next-due timer (internal/jobs, Scheduler.arm) |
the server process, from server start (one parked goroutine, no timer at idle). It dispatches nothing until its start gate opens: the reconciler's first resync has applied the routes (step 10: list, inspect, the fast rules, the state map and the first route apply, the buffered events; before the removals and starts, which follow and delay nothing; a stop-first deploy interrupted after its start stage is flagged versions_kept by the boot pass so a restart or deploy queued behind the gate is refused until the resync has settled it; with Docker down at start it stays closed and the watcher retries with its back-off) |
one time.Timer, set to the earliest run_after of a queued job that is not yet due and stopped when there is none |
never at idle. It exists only while a transient pull retry (15 s, then 60 s), an M4a domain job (domains_pause, debounced 2 minutes after the first failure that qualifies; domains_resume, on the earliest paused_until, rounded up to 15 minutes, which can be up to 7 days away: the cert_retry_after cap) or, from M6, a cron job is waiting. The two domain jobs are ordinary rows of the jobs table (at most one queued of each kind) found by this same timer; they add no timer of ours. A job that is due but blocked by a running job of its service needs no timer: the running job's end wakes the scheduler. |
Reconciler reconnect back-off (internal/deploy/reconciler.go, Reconciler.Run) |
the server process, one goroutine from server start (the reconciler loop: it holds the Docker events op open and handles events and per-service resyncs on the one goroutine) plus the goroutine that holds the events call itself while a connection lasts; both joined at shutdown |
1 s, 2 s, 4 s, 8 s, 16 s, 30 s, 30 s ..., jittered (each wait is between half and all of its step), reset after a connection that opened and resynced | only while the events stream is down. One time.Timer per wait, created when the stream ends or fails and gone when it fires (or when EnsureSynced asks for a reconnect now). While the stream is up there is no timer: events arrive on the open stream, the per-service resync after a job is requested by the job's end, and nothing polls (TestBackoffOnlyWhileDown). The reconciler has no health gate and no other timer: after it starts a stopped container the events stream keeps the state honest. A silent Docker hang with the stream still open (no event, no error) is not noticed by the reconciler (a heartbeat would be a timer); the next job's own calls, which all have deadlines, mark the service unknown, and every reconnect resyncs. |
Per-session goroutines (they exist because a session exists; none wakes on a timer of ours):
- The hub's drain goroutine per agent session (
attach): blocked inAcceptStream. Agents never open streams, so the first one ends the session. It exits with the session. - yamux's own send, receive and keepalive goroutines per session (the keepalive is the 30 s row above).
- The agent side serves each accepted stream in its own goroutine, at most 32 at once.
- The in-process local agent's two session goroutines in
runServer, joined before it returns.
Short-lived, event-driven goroutine, no timer: after each argon2 hash the hasher starts one goroutine that calls debug.FreeOSMemory (internal/auth/hasher.go), so the 19 MiB the hash used is returned to the OS off the response path; it exits at once.
The SPA's own timers run in the browser, not in the server:
- the footer status poll, every 15 s while the page is visible;
- the two-factor step warning;
- (M3a) the Deploy page's poll of
deploys.get, every 2 s only while the page is visible and the deploy is running (5 s after 2 minutes of pulling; it stops when the deploy finishes or the page is hidden). - (M4a) the shared
Poller(web/src/lib/domainwatch.svelte.ts, used by the domain watch on Service > Domains and Domain details and by Settings > Panel address): 5 s for the first 2 minutes, then 15 s, and it stops at 10 minutes (saying so, with a Refresh button, which restarts both the pacing and the 10 minutes), and only while a domain or the panel domain is "Setting up" and the page is visible. A tab that was hidden and is shown again loads once and keeps polling only inside the same 10 minutes. A failed poll sets an alert in place and halts. Once nothing is setting up there is no request from this Poller; Overview and the lists send none of their own while idle (Playwright counts requests), but the footer status poll above still runs.
The server has no timer, subscription or per-client state for any of them. Each poll is an ordinary request, and the Services list and Overview send no request while idle (a Playwright test counts requests over 30 s).
Bounded waits during a deploy only, no goroutine of ours (each is a time.Timer or an AfterFunc inside a job's own goroutine or one op, ended by its context, and gone when it finishes): the health gate's 1 s interval between checks (rundeploy.go, stopfirst.go), the pull stall timer that fails a pull with no new byte, status or layer for stall_s (internal/agentops), the one-health-interval wait for an oom event when a candidate was restarted by Docker during its gate (internal/deploy/rundeploy.go, restarted; a time.Timer inside the job, ended by its context), the 0.5 s read-slot wait of deploys.log (below), and a wait of at most 0.5 s in 10 ms steps for the local agent's session when a job starts before the agent has attached (cmd/serverdock/deploywiring.go). The drain of a blue-green deploy (internal/deploy/switch.go) is one time.Timer for exactly drain_s between the commit and the stop of the old container, inside the deploy job's own goroutine (ended early by a shutdown, or by a queued services.delete, which skips the rest of it); nothing waits at idle. The scheduler keeps 2 workers (jobs.MaxWorkers): a deploy holds its worker and the service lock for the whole drain (up to drain_s, 300 s at most), and a stop-first deploy holds them for its gap, so two services that are draining or in a gap can queue other services' jobs for up to that long. Accepted for M3a.
Lazy, no timer and no goroutine: the OOM tracker (OOMTracker, internal/deploy/oom.go: the events callback records into memory, the reconciler's own loop writes services.last_oom_at; at most 4,096 per-service timestamps (a full map first drops entries older than the coalescing minute) and a ring of 64 container ids, dropped with the service or on a flush that finds no row); deploy logs (internal/deploy/deploylog.go): the tail of a container's output is read once, when a container of a deploy is about to be removed, and written as one gzip file per deploy (the previous version's and an orphan's output after the container has stopped and before it is removed; a failed candidate's before its stop, and not at all at shutdown, where the resync keeps it; at most a third of the clean-up time left, 3 s in the stop-first gap). The files beyond a service's newest 10 deploys are deleted when a deploy finishes (and with the service); the first resync after a start removes the directories of services that no longer exist (files only, no timer, no goroutine). Deploy-log memory: a BestSpeed gzip writer is about 1.2 MiB, taken from a sync.Pool and used by at most 3 keeps at once (two jobs and the resync), so about 3.6 MiB transient, plus a 32 KiB copy buffer; the whole log is never held. deploys.log memory: the log is capped at 1 MiB in all (header and output), and one request costs about 5 MiB of heap for ordinary text, up to about 11.3 MiB for a log of lone invalid bytes (each becomes three bytes), and at most about 23 MiB with the two-read cap, all transient (TestDeployLogReadPeak, plan 0005 Revision 11), plus the JSON encoding in the action layer (the buffer is sized from the gzip trailer, then the cleaned copy, then the redacted copy); at most 2 reads run at once (MaxLogReads), a third waits 0.5 s and is told "try again in a moment" (503 unavailable). Deploy-log disk: at most 1 MiB uncompressed per deploy, so at most 10 MiB per service before compression: 1 GB in the worst case (10 × 1 MiB × 100 services), in practice a small fraction (logs compress several times over). This bound is the only disk budget. Not swept: a .tmp file left by a crash is removed only when a deploy of that service finishes later, so one for a service that never deploys again stays (at most 1 MiB), and the files of a service whose last deploy is long past stay until it is deleted. Session and pending-sign-in pruning (a bounded batch on insert), the last_seen_at write (at most once a minute, best-effort), the setup-token file (written at start while no admin exists), the panel certificate check (at start only) and the hub certificate renewal and its 1 minute back-off (internal/pki, checked in the TLS handshake); the rate limiters' eviction (internal/limits); the audit log's denied-row "suppressed" summaries (written on the next denied attempt or at shutdown); finished-job pruning (at most 100 per job insert) and deploy-row pruning (when a deploy finishes), the app subnet choice (first start, or when something first asks for it) and its overlap check (at each address allocation); the migration runner and its backup (startup only); the system.exposure answer (kept 30 s, its age checked on read, never refreshed by a timer); the app side's boot (deploy.Booter: network_ensure, then a request to the reconciler for its first resync, which lists and inspects the containers and opens the route gate; run once by one goroutine after the panel is up and joined at shutdown, and again lazily by a service action that finds the gate closed, which asks the reconciler to reconnect now instead of waiting out its back-off, never on a timer of its own); the startup wait on the data-directory lock (at most about 1 s).
Security model (summary)
Full threat model: security.md.
- Agent socket access to Docker is root-equivalent, so the agent has no listening ports; only outbound to the control plane.
- The hub's agent listener (
--agent-listen, off by default) is the only inbound agent surface: its own TLS 1.3 listener (not behind Caddy), a private hub CA the agent pins by fingerprint, a shared token checked after a per-IP failure limiter, session and connection caps, and a yamux ping guard. Remote agents are read-only (logsonly) until Phase 2. See ADR 0009. - Every operation is a registered action with a risk tier, a per-actor policy and an audit trail (intent row first, outcome row after); the audit log is hash-chained and
serverdock audit verifychecks it read-only. - The panel is served over HTTPS by the embedded proxy (a self-signed leaf of its own, never from the hub CA; the Host allowlist answers 421,
:80redirects and, since M4a, answers challenges) and reaches the control plane over a private unix socket; first run needs the console setup token (DATA/setup-token, 0600). - Secrets encrypted with a key kept outside the DB file; the key/data pair is shown to the user to back up.
- Auth (built in M2): argon2id passwords behind a one-at-a-time hasher, TOTP with recovery codes, opaque
__Host-session cookies (12 h idle, 7 d absolute) with a CSRF header and an exactOrigincheck, scoped API tokens that can never run sensitive or destructive actions, fresh 2FA for sensitive and destructive actions, sessions revoked on password or 2FA change,serverdock admin resetfor recovery. Passkeys come later (M4b, plan 0013). - WebSocket/terminal/MCP routes will use the same authz as REST (none exist yet); the route-matrix test (every route, 24 credential cases, also a subset through the real Caddy) runs in CI.
- Signed releases; SBOM; private vulnerability reporting.
Repository layout
* = existed after Phase 0; + = added in Phase 1 M1; ++ = added in Phase 1 M2; +++ = added or extended in Phase 1 M3a; the rest are planned.
cmd/serverdock/ * main: server | agent | version (prints `ui=spa|placeholder`); + audit verify; ++ admin reset; ++ the control and debug sockets (`socket.go`), `server.go` startup order, panel flags
internal/api/ * control-plane HTTP: the REST handler over the action registry (`/api/v1/actions/{name}`) and the generated OpenAPI 3.1 document (`docs/api/openapi.json` is its golden file, `make openapi`), the route table (every route and its AuthKind), Host/Origin/content-type/CSRF middleware, credential resolution, SPA serving with CSP, debug handlers; + header/body limits, /agent/* answers 404, the "from our proxy" connection mark (`WithTrustedProxy`)
internal/hub/ * server side of agent connections (WebSocket + yamux); + sessions cap, auth-failure limiter, stream caps, token rules
internal/agent/ * agent runtime: dial-out client, backoff, stream handlers; also used in-process by `server`; + op-spec table (RemoteOK), ping guard
internal/agent/proxy/ * embedded Caddy, owned by the agent runtime (ADR 0004); +++ `Applier` (`proxy_apply`: validation, bind isolation, no `caddy.Load` when only upstreams change), `app.go` (the `serverdock_app` handler and its in-memory table: one app server, one `reverse_proxy`)
internal/agent/dockerapi/ * Docker Engine API client over the unix socket (logs; + per-call deadlines, API negotiation, Stop); +++ images, containers, networks, events, the 64 KiB JSON-line cap
internal/pki/ + the hub CA, the hub leaf with lazy renewal, the agent-side pin check (ADR 0009)
internal/limits/ + keyed token buckets, lazy exponential back-off (`Backoff`), client-IP keys (X-Forwarded-For only from the marked control socket), a connection-capping listener
internal/store/ * SQLite (WAL); + forward-only migrations (migrations/NNNN_name.sql), pre-migrate backup, one-server lock, read-only open, testdata/ fixtures
internal/audit/ + hash-chained audit log, verify, denied-row rate limit, the intent/outcome flow
internal/redact/ + removes secrets from audit rows, errors and logs
internal/auth/ ++ argon2id hasher (bounded semaphore, fast 503), PHC parsing, TOTP, recovery codes, the setup token, sessions, the pending-2FA state, API tokens, and the auth actions (`authactions.go`); the HTTP endpoints for these are in `internal/api/authhandlers.go`
internal/datadir/ ++ creates and checks DATA (0700, owned by the running uid), the secret-path list, atomic file writes
internal/secretbox/ ++ AES-256-GCM sealing under DATA/keys/master.key, with the missing-key and wrong-key refusals
internal/testbin/ ++ test-only harness: builds and runs the real binary (umask, file modes, exit codes, other uids)
internal/actions/ + action registry (with the JSON Schema reflector, `schema.go`): risk tiers, policy, SystemInvoker, built-in read actions (shared by API, MCP, AI)
internal/memstat/ * /proc/self/status + Go runtime stats (heap in use, idle and released; read through the debug socket by the idle-memory check)
internal/mcp/ MCP server
internal/ai/ assistant loop, redaction, approvals
internal/deploy/ +++ the image-source deploy pipeline: services and deploy actions (`services.go`, `deployactions.go`, `deployreads.go`), the runner (`runner.go`; pull, check, start, health gate in `rundeploy.go`; switch, commit, drain, stop old in `switch.go`; `stopfirst.go`; `restart.go`; `delete.go`), the snapshot and container spec (`snapshot.go`, `spec.go`), the app network, subnet and address allocator (`subnet.go`, `alloc.go`), the route lock and route generation (`routes.go`), deploy logs (`deploylog.go`), and the reconciler (`reconciler.go`: the events watcher and its state map; `resync.go`: the resync rules; `reconcileactions.go`: its two system-only actions; `interrupted.go`: the boot pass; `locks.go`: the lock order; `boot.go`: the app-side boot, `network_ensure` and the first resync request)
internal/jobs/ +++ the durable job queue and the scheduler (one "next due" timer, two workers, one running job per lock key, the start gate), actors stored in jobs, lazy pruning
internal/agentops/ +++ the `LocalOnly` Docker and proxy ops of op protocol v1 (agent side, `handlers.go`, `proxyapply.go`) and the typed client the control plane calls them through (`client.go`); ownership by label, the exact-bytes create check, address checks (`addr.go`); the wiring of all of it into the server is `cmd/serverdock/deploywiring.go`
internal/policy/ +++ default-deny rulebook (no state, no background work): name, image reference, registry host, port and health-path validators, resource caps, `CheckImage`, `CheckCreate` (run in the control plane and again in the agent on the exact create bytes)
internal/build/ railpack/buildkit, builder selection
web/ ++ SvelteKit SPA (Svelte 5, static adapter, SPA fallback). `go build -tags spa` embeds `web/build` (embed_spa.go); without the tag `web/dist/index.html` is the placeholder (embed_placeholder.go). Node is needed only to build it (`make web`, `make dev`, CI). `e2e/` holds the Playwright + axe suite, `src/lib/api-types.ts` is generated from `docs/api/openapi.json`
bench/ * Dockerfile (builds with `-tags spa` and asserts `ui=spa`), run.sh, measure.sh, results/; ++ after-login.sh and idle-memory.sh (report-only M2 checks)
templates/ one-click app catalog + CI tests
.github/workflows/ * ci.yml (+ `screens-hash`/`screens-capture`: freshness of the website's screenshots, a warning at first); + site.yml (website build; not a required check); + .github/scripts/ (bench trigger), CODEOWNERS, dependabot.yml
site/ + the public website (plan 0014): a static Astro site with no client JS, built from `docs/*.md` and deployed to Cloudflare Pages. Not embedded in the binary and not benched; `site/deploy/` holds the deploy CLI with its own lockfile
docs/ vision, features, architecture, roadmap, research, plans, decisions, api/openapi.json (generated golden)