Deployment Architecture (per-country, self-hosted)
Status: living reference (engineer-facing). Last updated 2026-06-08.
Design records (rationale, point-in-time): docs/specs/2026-06-07-per-country-deployment-automation.md,
docs/specs/2026-06-07-host-based-spa-serving-design.md.
Operator steps: docs/runbooks/provision-deployment.md.
OpenGov runs one isolated instance per country deployment (a country × project,
keyed by code, e.g. let-cob). Each instance is a self-hosted Docker-Compose stack.
This doc explains how a deployment is described, boots itself, gets routed, and is onboarded.
1. A deployment is a committed git artifact
Everything country-specific lives in deployments/<code>/, committed to the repo (so it
ships inside the image and there is one source of truth):
deployments/<code>/
├── config.yaml # identity + wildcard_base + Coolify target (non-secret)
└── secrets.env # SOPS+age encrypted (POSTGRES_PASSWORD, OIDC client secret, KEK, …)
config.yaml (src/opengov/platform/deployments/artifact.py → DeploymentArtifact):
| Field | Purpose |
|---|---|
code, country_iso2, project_slug, display_name, timezone, default_locale, supported_locales, status | Identity — byte-identical to the deployments registry row |
wildcard_base | e.g. services.example.gov. Every component host derives from this |
coolify.{project_uuid,server_uuid,github_app_uuid,git_repository,git_branch,compose_service_name} | Coolify deployment coordinates |
Derivation (fixed platform convention). From wildcard_base, the artifact derives the five
component hosts, the login host, the assistants door host and all OIDC env — there is no
per-host hand-wiring:
| Subdomain | Serves | KC client | OPENGOV_*_URL |
|---|---|---|---|
smartrules.<base> | SmartRules editor SPA | opengov-editor | OPENGOV_EDITOR_URL |
approval.<base> | eApproval SPA | opengov-approval | OPENGOV_APPROVAL_URL |
applicant.<base> | eRnext portal SPA | opengov-portal | OPENGOV_PORTAL_URL |
smartlink.<base> | SmartLink admin SPA | opengov-smartlink-admin | OPENGOV_SMARTLINK_URL |
studio.<base> | Registers Studio SPA | opengov-studio | OPENGOV_STUDIO_URL |
login.<base> | Keycloak (oidc service) | — | OPENGOV_OIDC_ISSUER / OIDC_HOSTNAME |
mcp.<base> | The assistants door (/mcp) — no SPA | opengov-mcp (loopback PKCE) | OPENGOV_MCP_PUBLIC_URL |
The component label → SPA map is enforced to match spa_router.HOST_SPA by a test, so the
artifact, the app host-router, and the Keycloak redirect URIs cannot drift.
Secrets are SOPS-encrypted with age (no cloud KMS → air-gap-safe; .sops.yaml). They split
into two tiers: Coolify-tier (pushed to Coolify) and KEK-tier (OPENGOV_ENCRYPTION_KEY,
OPENGOV_ANON_HASH_SALT, OPENGOV_VAULT_KEK_V*) which are never sent to Coolify — the operator
injects them out-of-band, mirroring backup.sh’s “DB dump and KEK never in the same place” design.
A pre-commit guard refuses to commit a plaintext secrets.env or any *.agekey.
2. The compose stack self-bootstraps at boot
docker-compose.yml services:
postgres → { opengov, worker } each waits for the database, then one of
them migrates while the other waits
oidc (Keycloak) → init-keycloak blocks nobody
- Each service that needs a migrated schema boots itself (
opengov.entrypoint, in front of the real command): wait until Postgres accepts a connection → take a Postgres advisory lock, a lock held in the database itself so exactly one container proceeds → runpython -m alembic upgrade heads→ apply the Procrastinate schema (not in the Alembic migrations; seedev.sh) → seed this deployment’s registry row from its committed artifact (keyed byOPENGOV_DEPLOYMENT_CODE) → release the lock → become uvicorn (or the worker). Every step is idempotent, so the container that waits finds the work done. - This fixes three things that otherwise made a fresh prod stack un-bootable:
- the
main.pysys.exit(78)deadlock (nodeploymentsrow → fail-loud boot, PR #237), - no migrations ever ran in the bare prod compose,
opengov+workerracing to create the schema.
- the
- Why not a separate one-shot container? It was one until 2026-08-11 (an
initservice the app waited on viadepends_on). Docker Swarm discardsdepends_onentirely, so “wait for that one to finish” is an instruction it cannot follow — and D47 moves the sandbox to Swarm. The lock expresses the same guarantee without needing an orchestrator to order anything, and behaves identically under plain Compose, which is where it runs first. Spec:docs/specs/2026-08-10-docker-swarm-default-deployment.md§4.2. - First admin login (opt-in). The realm imports with zero users, so
init-keycloakseeds a first Keycloak login whenOPENGOV_SEED_ADMIN_PASSWORDis set — creatingOPENGOV_SEED_ADMIN_EMAIL(defaultadmin@opengov.local) withOPENGOV_SEED_ADMIN_ROLES(defaultadmin). It is non-fatal (a KC error is logged, never blocks boot — only the registry-row seed is a hard gate) and idempotent (KC-26 sequence: create → reset-password → assign roles). This is whyinit-keycloakdepends_onoidc: service_healthy— and why it is a separate container: nothing waits for it, so it is free to be slow. Under Swarm, wheredepends_onis discarded, it waits for Keycloak itself (bootstrap_deployment._wait_for_keycloak, 120s bound). oidcbuilds fromkeycloak/Dockerfile(FROM keycloak/keycloak:26.8) and copies the realm JSON into the image. A./keycloakbind-mount does not survive a PaaS deploy because it resolves to the orchestrator’s app directory, not the repo. The image runskc.sh buildat build time and bootsstart --optimized --import-realm(production mode, strict hostname). The import still substitutes${OPENGOV_*_URL}from runtime env, so each deployment receives its redirect URIs.- Rights administration (spec 2026-07-28-user-rights-admin). The rights API
(
/api/v1/platform/rights/*) logs into Keycloak as theopengov-rights-adminservice-account client, configured on theopengovservice viaOPENGOV_KC_ADMIN_CLIENT_ID(defaultopengov-rights-admin) andOPENGOV_KC_ADMIN_CLIENT_SECRET(no default — when unset the rights routes answer 503 “not configured” in plain words, never a silent fallback). The client is created two ways, both idempotent:--import-realmon fresh deployments (secret substituted from theoidcservice’s env), andinit-keycloak’s realm reconcile on existing ones (secret substituted from that container’s env — keep all three services on the same value). The reconcile also wires the service account’srealm-managementview-users+manage-usersroles — no operator step in Keycloak is required. Secret rotation: set the new value on the Keycloak client’s Credentials tab (or delete the client and let the nextinit-keycloakrun recreate it), then update the env onopengovandinit-keycloaktogether.
No service publishes a host port. Containers expose internal ports only; a reverse proxy (Coolify’s Traefik, or a standalone proxy on a bare VPS) terminates TLS and routes the deployment’s domains to internal ports. Publishing fixed host ports collides on a shared/multi-tenant host and bypasses TLS termination (PR #252).
The login host refuses /admin to the internet. The admin console and the
admin API of the login service are under /admin. An additive proxy route
(scripts/render_login_admin_route.py) refuses them on login.<base> with 403.
All other paths stay public, for example /realms/ and /resources/. The app
and init-keycloak call the admin API at http://oidc:8080, so the route does
not touch them.
Admins open the console through an SSH tunnel to http://localhost:18088. The
provisioning env gives Keycloak this address as KC_HOSTNAME_ADMIN. The
Credentials tab of the rights paragraph above is in this console too.
Procedure: docs/runbooks/provision-deployment.md steps 8 and 9. Design note:
docs/specs/2026-10-13-login-admin-console-not-public.md.
When the application container cannot answer, the proxy shows a designed page, not bare error
text. The SPAs are served by the opengov container, so while it is down there is no application
left to render a friendly message — the proxy has to. The page (deploy/error-page/unavailable.html,
this country’s wordmark and emblem baked in) is served by a host systemd service
(deploy/error-page/opengov-offline-page.service, installed by scripts/install-offline-page.sh,
#2686) — deliberately OUTSIDE the application’s own compose stack, so a redeploy of the application
does not tear the page down with it. scripts/render_offline_page.py renders the page and its
Traefik dynamic-config route from the deployment’s own committed config.yaml; the installer copies
the route to /data/coolify/proxy/dynamic/ (a host-side step, like the registry route, not part of
the compose up) and proves the page answers before reporting success. The page reloads itself once
/health answers again. Full procedure: docs/runbooks/offline-page.md.
The in-app errorpage compose service (the sentinel image serving the same static file) is kept
running until the host service is confirmed serving on the sandbox, then removed — see the comment
above it in docker-compose.yml.
Honest limit: if the container engine itself is down on the host, there is no proxy and no page — this design covers a redeploy or crash of the application, not the whole host going dark.
Boot invariants (fail-loud)
The opengov lifespan (src/opengov/main.py) refuses to boot on misconfig, in order:
- OIDC consistency —
OPENGOV_OIDC_ISSUER+OPENGOV_OIDC_AUDIENCEmust be set (auth-on). - Deployment row —
OPENGOV_DEPLOYMENT_CODEmust resolve adeploymentsrow (else exit 78). - Timezone —
ZoneInfo(timezone)must resolve → the runtime image bundlestzdata(the minimal Chainguard image ships none; PR #252).
3. Host-based SPA serving (one image, five SPAs, by Host)
The opengov container serves all five SPAs and /api. Which SPA is served is chosen by the
request Host (src/opengov/platform/spa_router.py):
- A middleware (after CORS, GET/HEAD only) maps the Host’s first label → that SPA’s
static/<dir>. - Passthrough (never intercepted):
/api,/health,/version,/config.json,/docs,/redoc,/openapi.json. (All backend routes live under these.)/metricsis deliberately NOT passthrough — the public app owns no such path at all; the measurements are served on a separate internal listener (§8), never routed here. - A known SPA host serves the requested file, else
index.html(200) — this resolves client routes,/callback, and deep links. Path traversal is blocked. - Unknown host fails closed (404 + WARNING).
- Installed only when a SPA build exists, so dev/test (no
static/) are unaffected.
The SPAs are built with base = VITE_BASE ?? '/' and <BrowserRouter basename={import.meta.env.BASE_URL}>,
so they serve at a subdomain root. static_root resolves from CWD (/app/static), not the
package path (__file__ is /install/... in the image).
Runtime OIDC config — GET /config.json
The SPAs do not bake OIDC config at build time (that shipped the authoring SPAs auth-bypassed
when the build var was missing, because AuthProvider treated a missing authority as dev mode). Instead:
- The backend serves
GET /config.json(public, no secrets) from its runtimeOPENGOV_OIDC_*env, returning a per-Hostclient_id(smartrules.→opengov-editor, etc.). AuthProviderfetches it before initializing OIDC and hard-fails on a missing/broken config — never the dev stub.redirect_uriauto-derives fromwindow.location.origin/callbackper subdomain.- Result: one image serves all 11 countries; the only per-deployment input is runtime env.
4. Onboarding a deployment (Coolify)
scripts/provision_country.py deployments/<code> (CLI over coolify_client.py + onboard.py):
- loads the artifact +
sops-decryptssecrets.env(splitting KEK out); - find-or-creates the dockercompose app from the artifact’s
git_repository/git_branch; - pushes the Coolify-tier env (deployment code + the five
OPENGOV_*_URL+ OIDC issuer/hostname, all derived fromwildcard_base) — never the KEK tier; - sets the Coolify domains: the five SPA hosts as one comma-separated value → the
opengovservice, andlogin.<base>→ theoidcservice (Coolify routes multiple FQDNs per service only via a comma-separateddomain); - deploys and waits for a terminal status.
Manual, browser-only (cannot be scripted): the Coolify API token, the GitHub App connection, and injecting the KEK-tier secrets out-of-band. See the runbook.
Coolify gotchas (learned the hard way)
- Coolify caches the parsed compose at app-creation — a compose change needs the app recreated, not just redeployed.
docker_compose_domainsset before the first deploy don’t persist (compose-parse nulls them) — set them after the first deploy, then redeploy.- The deploy branch must be pushed to origin (Coolify clones from GitHub).
docker pull keycloak/keycloak:26.8pulls the official KC image from Docker Hub. The:26.8tag floats to the latest patch. Pin:26.8.x@sha256:<digest>if reproducible KC builds matter.- Webhook auto-deploy is OFF for the sandbox (wave 5): the post-deploy-smoke workflow is the
sole deploy owner (stamp
SOURCE_COMMIT→/deploy→ smoke, one build per merge). Rollback and the manual/deploypath:docs/runbooks/post-deploy-smoke.md§Deploy topology. - Coolify 4.1.2 compose builds never export
SOURCE_COMMITto the build env — the app env is the only channel (stamped by the workflow per above); the in-imagegitshastage is the fallback and stampsunknownwhen the PaaS checkout hides.gitfrom the build.
5. Day-2 ops
- Backups:
scripts/backup.sh(pg_dump custom-format + the world-model volume + KC realm export; KEK kept out-of-band) /scripts/restore.sh. Scheduled byscripts/install-backup-timer.sh(systemd timer, nightly, verifies its own first run). Postgres holds nearly everything, including the Procrastinate queue — but not the generated migration files an approved model publish writes into the world-model folder, which is why that volume travels in the same bundle (issue #1788). Runbook:docs/runbooks/backup-restore.md. - Provisioning the host:
scripts/vps_bootstrap.sh(idempotent). - TLS: the reverse proxy (Coolify/Traefik ACME, or
step-cafor air-gap) — see the deployment- automation spec for the fleet/day-2 roadmap (Phases 2–4: fleet CD, object-storage backups, k3s).
6. Where things live
| Concern | Module / file |
|---|---|
| Artifact schema + derivation | src/opengov/platform/deployments/artifact.py |
| Registry upsert (seam) | src/opengov/platform/deployments/service.py |
| Boot bootstrap (per-container) | src/opengov/entrypoint.py, src/opengov/bootstrap_deployment.py |
| Host-based SPA router | src/opengov/platform/spa_router.py |
| Runtime OIDC config | GET /config.json in src/opengov/main.py |
| Coolify client | src/opengov/platform/deployments/coolify_client.py |
| Onboard orchestration + CLI | …/deployments/provision.py, scripts/provision_country.py |
| Secrets tiering + guard | …/deployments/secrets.py, scripts/check_secrets_encrypted.py, .sops.yaml |
| Compose + images | docker-compose.yml, Dockerfile, keycloak/Dockerfile |
| Frontend OIDC | frontend/shared/auth/AuthProvider.tsx; per-SPA vite.config.ts + main.tsx |
PR trail: #237 (init self-seed) · #240 (worker async connector) · #245 (procrastinate schema) · #252 (drop host ports + tzdata) · #275 (host-based SPA serving + runtime OIDC + KC realm bake + wildcard_base wiring).
8. Reading a deployment’s own numbers (the metrics listener)
In plain words: the opengov app and the worker each open a small extra doorway,
reachable only from inside the deployment’s own Docker network, where a country’s own
monitoring can read the counts the platform already keeps. Full detail (per-target
ownership, labels, the two traps): docs/reference/metrics-scrape-contract.md.
- One listener per process, both on port
9100, both bound0.0.0.0inside their own container:src/opengov/platform/metrics_server.py::start_metrics_listener, called frommain.py’s lifespan (component="app") andworker.py’smain()(component="worker"). Gated byOPENGOV_METRICS_ENABLED(defaultFalse;docker-compose.ymlsets ittrueon both services). - The worker’s listener is not optional. Most of the interesting numbers — every queue-depth and payment-hold gauge — are counted in the worker, never the app. An app-only listener would answer with mostly zeros and hide exactly the backlog an operator needs at 3am.
- Published nowhere, routed by nothing — two independent layers, both required:
docker-compose.ymladds nothing toexpose:for port 9100. Compose’sexposepublishes no reachability by itself (any container on the network already reaches a listening port); what it WOULD do is makecoolify_client.py’sdocker_compose_domains(which carries no port) ambiguous about which port the four SPA hostnames route to. The wrong answer there is the exposition served on a public hostname.spa_router.py’sPASSTHROUGH_PREFIXESdeliberately excludes/metrics(§3) — the public app has no such route at all, so there is nothing for a passthrough entry to route to, and a future accidental mount on a known SPA host still resolves to the SPA shell rather than the exposition (defence in depth).
- No authentication on the listener. The exposure model rests entirely on the port
being unreachable from outside the deployment’s network — read the scrape contract
before trusting the
0.0.0.0default in any topology where that assumption might not hold. - Reading it from a shell-less container (same idiom the healthcheck uses):
docker compose exec worker python3 -c \ "import urllib.request as u; print(u.urlopen('http://127.0.0.1:9100/metrics').read().decode())" - Single-uvicorn-worker is load-bearing.
docker-compose.yml’sopengovcommand has no--workersflag, so exactly one process holds the one Prometheus registry behind port 9100. Adding--workers Nwould put N processes behind one port, scraping one arbitrary worker’s numbers.