Skip to content

7. The control plane

Everything above drives one spec you point pstack at. A host that serves several projects and many PRs needs a second idea: deployments with identities, a kind that decides what may be done to them, and preconditions between them.

control-plane.md has the architecture. This section is the operator’s view.

The blocks in this subsection are the shape init prints; unlike the rest of the guide they were not captured here, because init needs a real host, a real domain and a running Docker.

pstack init creates the control stack — Traefik plus the pstack API/UI container, in compose project pstack-control — from the host. The minimum is a domain and an ACME address. No DNS credential: HTTP-01 is the default.

Terminal window
pstack init --domain preview.example.com --acme-email <you>@example.com

DNS-01 is opt-in, and the provider is required only then:

Terminal window
PSTACK_DNS_TOKEN=<token> pstack init \
--domain preview.example.com --acme-email <you>@example.com \
--challenge dns01 --dns-provider cloudflare

The two inputs go to different places, on purpose. --dns-provider is lego’s provider code and is an ordinary flag (or PSTACK_DNS_PROVIDER). The credential never goes on the command line — it travels in PSTACK_DNS_TOKEN or --dns-token-file <path> (a path is not a secret; the token would be, and argv is readable by every user on the box through ps). init writes it to control/dns.env at mode 0600 under the variable name that provider expects. Traefik loads that file through env_file:; the pstack container deliberately does not mount it, so the credential reaches the thing that needs it and nothing else.

route53 and gcloud are tokenless — the instance profile or the attached service account satisfies the credential chain, so omit PSTACK_DNS_TOKEN entirely. For any provider outside the verified list, init writes CHANGEME_VARIABLE_NAME= rather than guessing the name, because a wrong one fails as an ACME propagation timeout and sends you debugging DNS instead of a typo.

The verified provider→variable table, the Cloudflare permission pair, and what to do when a provider needs more than one variable are in bootstrap.md §3 → Switching to DNS-01.

Everything init reads:

Flag Environment Default Notes
--domain <apex> PSTACK_DOMAIN — required. Hostnames are derived from it: control.<domain>, api.<domain>, <service>.<domain>, <surface>-pr-<n>.<domain>
--acme-email <addr> PSTACK_ACME_EMAIL — required. Let’s Encrypt mails expiry warnings here
--challenge http01|dns01 PSTACK_CHALLENGE http01 see Choose a TLS mode. Anything else exits 3
--dns-provider <lego-code> PSTACK_DNS_PROVIDER — required for dns01 only, ignored by http01
--orchestrator swarm|compose PSTACK_ORCHESTRATOR swarm how previews deploy. swarm makes this daemon a one-node manager (overlay networks, the swarm provider in Traefik); compose is what every host before 0.26.0 ran. upgrade keeps whatever the host has — see Swarm mode
--logging none|loki PSTACK_LOGGING none loki: a Loki service in the control stack, its log plugin on this node, and a logging: block on every deployed service that has none. Anything else exits 3. upgrade keeps whatever the host has
--ingress-subnet <cidr> PSTACK_INGRESS_SUBNET 10.250.0.0/16 swarm only: the address range of preview-ingress, which every routed preview service takes an address on. Used when the network is created; an existing network is kept as it is unless you set this, and then one with a different range is re-created — every preview must be asleep or down first, and init stops naming the ones still attached. See the address leak
--shared-subnet <cidr> PSTACK_SHARED_SUBNET 10.251.0.0/16 the same, for preview-shared
--previews-on workers|any PSTACK_PREVIEWS_ON unset swarm only. workers labels this manager pstack.previews=off, so it runs only the control stack and every preview lands on a worker; any undoes it. Unset leaves the manager as it is, so pstack upgrade never changes it. With no worker yet, previews stay pending until one joins (init says so). Under compose it exits 3
— PSTACK_DNS_TOKEN unset the DNS-01 credential, written to dns.env. Omit for the tokenless providers
— PSTACK_TOKEN generated the API bearer token. Supply it to keep or rotate a known one; leave it unset to be handed a fresh one printed exactly once
— PSTACK_LOKI_PASSWORD generated with --logging loki: the push password (32 lowercase hex), kept in control/.env as LOKI_PUSH_PASSWORD. Supply it to keep the host’s
— PSTACK_IMAGE pstack:local the control image. A property of the installation, not the host
— PSTACK_DATA /var/lib/pstack where the registry and the control stack’s config live

-n / --dry-run, -v and -q behave exactly as they do everywhere else. Two secrets, two blast radii: PSTACK_DNS_TOKEN can edit a DNS zone; PSTACK_TOKEN drives an API holding a read-write Docker socket, i.e. root on the host. They are never the same value and live in different files.

What it does, in order:

Step Detail
0. Preconditions Docker socket at /var/run/docker.sock, the Compose v2 plugin, and the control image present; with --logging loki, grafana/loki and grafana/grafana, pulled if missing. Fails by name, before anything is created — run pstack build-image if the image is missing — it builds from the installed package, no checkout needed
1. State dirs <data>/deployments (the registry), <data>/control/traefik-dynamic (Traefik’s file provider, created empty so the mount does not fail) and <data>/control/loki (0755, in every mode; pstack mounts it read-write at /etc/loki)
1b. Swarm under --orchestrator swarm: docker swarm init if this daemon is not already a manager. Never leaves a swarm
1c. Loki plugin only with --logging loki: installs grafana/loki-docker-driver:3.7.7 on this node as loki and enables it — skipped when present, enabled when disabled. A failure fails init: under compose every logged service would fail to create
2. Networks preview-ingress and preview-shared, created idempotently — bridge under compose, overlay --attachable under swarm. A network that exists with the other driver is swapped only when nothing but the control stack is on it; a preview still attached is a hard stop naming it. Both must be declared external: true in every per-PR compose file — declare one non-external and Compose silently makes pr-123_preview-ingress instead, so the container comes up healthy and unreachable
3. Config control/docker-compose.yml (the template, with the challenge, UI, swarm-provider and wake-router blocks rendered), control/.env (0600, holds PSTACK_TOKEN and PSTACK_ORCHESTRATOR), control/dns.env (0600, holds the DNS credential; written either way so switching modes needs no extra step). Traefik gains a metrics entrypoint on :8082 (unpublished; the API reads it for sleep.idle) and the pstack container the catch-all pstack-wake router. With --logging loki: the loki service, control/loki/config.yaml (0644 — Loki runs as uid 10001; no credential; written only when absent) and LOKI_PUSH_PASSWORD in .env (PSTACK_LOKI_PASSWORD, or 32 generated hex characters), and the grafana service with control/grafana/datasources/loki.yaml (0644)
4. Up docker compose -p pstack-control -f <path> up -d --remove-orphans
5. Prove it polls the container’s HEALTHCHECK for ~60s. up -d exits 0 as soon as containers are created, so a crash-looping API would otherwise be reported as success
6. Next steps the URLs, the rotation recipe, and the generated PSTACK_TOKEN — the only time it is printed

It is idempotent: re-running it is the supported way to change the domain, rotate PSTACK_TOKEN, switch challenge mode, or move to a new image. (chmod is re-applied unconditionally, so a .env someone loosened to 0644 is tightened back on the next run.)

Terminal window
PSTACK_TOKEN=<new> pstack init --domain preview.example.com --acme-email <you>@example.com

control.<domain> serves one of three UIs. api.<domain> always serves the basic one.

Mode What Image
basic Embedded in the API. Default; no extra container. none
advanced The full SPA, its own container. pstack-ui:local (PSTACK_UI_IMAGE)
hearth The same product on Hearth UI, its own container. pstack-ui-hearth:local (PSTACK_UI_HEARTH_IMAGE)
Terminal window
$ pstack build-image --ui hearth # bare --ui builds advanced
$ pstack init --ui hearth --domain preview.example.com --acme-email ops@example.com
$ pstack ui hearth # switch an existing host; basic | advanced | hearth

hearth and advanced share the compose service name advanced-ui; only the image differs. Switching between any two modes is the same re-init that pstack ui already does. @samyx/preview-stacks-ui-hearth is published to npm with each release, so cloud-init --ui hearth and upgrade build its image the way they build advanced. From a checkout, use --ui-dist apps/ui-hearth/dist (its nginx.conf sits beside dist/), or docker build -f apps/ui-hearth/Dockerfile -t pstack-ui-hearth:local . from the repo root.

Terminal window
$ ssh preview-host
$ pstack upgrade # to the latest published version
$ pstack upgrade --to 0.25.1 # or an exact one
$ pstack upgrade -n # print the plan, change nothing

pstack upgrade runs that release’s installer (checksum-verified, into the directory the running binary lives in), then re-executes itself as the new version for the rebuild and the re-init.

⚠️ The one-time move from the Bun runtime (≤ 0.28.0 → 0.29.0)

Section titled “⚠️ The one-time move from the Bun runtime (≤ 0.28.0 → 0.29.0)”

Until 0.28.0 pstack was an npm package running on Bun; from 0.29.0 it is one static Go binary on GitHub Releases, and bun install -g cannot install it. On a host provisioned before 0.29.0:

Terminal window
$ pstack upgrade # first, to 0.28.0 if not there yet (the bridge release)
$ curl -fsSL https://github.com/samishal1998/preview-stacks/releases/download/v0.29.0/install.sh | sh \
&& pstack upgrade --resume # installs the binary, then phase 2: rebuild + re-init, token intact

0.28.0’s pstack upgrade --to 0.29.0 prints exactly that line and exits 3, so there is no way to miss it. Everything on disk is read unchanged — the registry, the SQLite database (every password hash keeps verifying), control/.env and control/dns.env — and nothing rotates. Things that DO change, and are worth a glance before you run it:

  • The control container no longer carries bun, bunx or a JavaScript runtime. Axis hooks run inside that container, so a hook that called bun/npx/node must bring its own: grep your specs (grep -E '\b(bun|bunx|node|npm|npx)\b' deployments/*/spec.yml) before the hop. bash, curl, docker and docker compose are there as before.
  • build-image no longer fetches from npm: the generated Dockerfile runs the release’s own install.sh, pinned to this version, in an empty context. It therefore needs the release to be reachable at build time; PSTACK_BINARY=<path> copies a local binary in instead. The previous image is kept as pstack:local-previous first, every time.
  • Rendered cloud-configs from ≤ 0.28.0 install the old runtime; re-render with pstack cloud-init before provisioning a new host.

Rollback, should the new image come up unhealthy:

Terminal window
$ docker tag pstack:local-previous pstack:local
$ docker compose -p pstack-control -f /var/lib/pstack/control/docker-compose.yml up -d

The first hop has to be by hand on very old hosts, because a host cannot run a command it does not have yet: on a box older than 0.25.1, pstack upgrade is simply not installed. Install the binary with the line above, then use the command from then on.

0.25.1 and 0.25.2 detected the UI mode by looking for a compose service named pstack-ui — a name that only ever appears as a Traefik router, so every host read as basic and the upgrade removed the advanced UI container it was meant to preserve. Fixed in 0.25.3, which reads the real service name (advanced-ui). To put a flipped host back:

Terminal window
$ pstack ui advanced

That switches which UI control.<domain> serves, reusing the stored token and domain, and building the SPA image on the way in. It does not touch the version — that is upgrade — and it recreates nothing when the host is already in the mode you asked for. pstack ui basic goes back; it builds nothing, since the API already carries the embedded UI. pstack upgrade --ui advanced does the same override as part of an upgrade.

It reads <DATA_DIR>/control/.env for the existing token, domain and ACME email, and reads the generated control/docker-compose.yml for the challenge mode and whether the advanced UI is running — then installs the new version, rebuilds the image (or both images), and re-runs init with exactly those settings.

Reading them back is the point. The upgrade was always three commands, and the third had a trap: init takes PSTACK_TOKEN from the environment and mints a fresh one when it is absent, so a hand-typed pstack init --domain … --acme-email … silently rotates the machine token and every CI job starts getting 401s — from a command whose purpose was “change nothing but the version”.

Two things worth knowing:

  • It runs in two phases, and the second is a real new process (pstack upgrade --resume, which you can also run by hand). build-image pins the image to the running CLI’s version, so a single process would install the new version and then faithfully build an image of the old one — an upgrade that reports success and moves nothing.
  • It is CLI-only, like init, and for the same reason: the API is a container inside the stack being recreated, so a self-upgrade kills the process mid-request and a broken image leaves the host with no control plane and no remote way to repair it.

Your data survives — deployments and the SQLite database are host-path mounts under DATA_DIR, not container filesystem. In-flight job history does not: it is in memory by design, so do not upgrade mid-deploy.

Because init renders from its arguments alone, a re-run that omits a flag takes that flag’s default, host-wide, without saying so — a new machine token, a blanked DNS credential, an advanced UI reverted to basic. From 0.37.0 init refuses that:

Terminal window
$ pstack init --domain preview.example.com --acme-email ops@example.com
refusing to re-init: this would change 3 thing(s) about a host that already exists, and you
did not ask for any of them.
the machine token
the one this host has → a NEWLY GENERATED one
keep it with: PSTACK_TOKEN=$(. /var/lib/pstack/control/.env; echo "$PSTACK_TOKEN")
the ACME challenge
dns01 → http01
keep it with: --challenge dns01
the web UI
advanced → basic
keep it with: --ui advanced

It refuses omissions only. A flag you spelled is a decision and passes through — --challenge dns01 on an http01 host is still how you switch modes — a first init has nothing to compare against, and pstack upgrade supplies every value it read back, so it never trips. --force proceeds anyway.

On a Loki host it refuses two more:

  • Loki logging — a run without --logging loki removes Loki. Keep it with --logging loki; --logging none turns it off on purpose.
  • The Loki push password — a run that keeps Loki without PSTACK_LOKI_PASSWORD mints a new one, and running containers’ pushes are refused until each stack is redeployed. Keep it with PSTACK_LOKI_PASSWORD=$(. /var/lib/pstack/control/.env; echo "$LOKI_PUSH_PASSWORD").

Turn Loki logging on or off: pstack logging

Section titled “Turn Loki logging on or off: pstack logging”
Terminal window
$ pstack logging loki # Loki on this host
$ pstack logging off
$ pstack logging loki -n # print the plan, change nothing

Like pstack ui, it re-runs init from what control/.env and the generated compose already hold, so the token, the DNS token and the domain stay as they are. Asking for the mode the host is already in recreates nothing.

loki adds a Loki service to the control stack, installs and enables the loki log plugin on this node, and writes a push password to control/.env. If the plugin does not install, the switch fails and says so. From then on, a deploy gives every service without a logging: key of its own the loki driver, labelled service_name=<stack>-<service>. A service with its own logging: is left alone and named in the job log. Deployments already running switch on their next deploy, a sleeping one on wake.

off removes the Loki service; the plugin stays installed. New deploys get no driver. Containers still running with it push to loki.<domain> and get a 404, which the plugin does not retry: their logs are dropped and stopping them is not delayed. The command prints how many deployments still carry the driver — each registry deployment’s compose.generated.yml, so it counts deployments the API has stored, not containers. Each drops it on its next deploy, a sleeping one on wake. It also leaves the pstack-control_logs docker network behind (harmless, not pruned); the loki volume is left on purpose, for a later pstack logging loki to reuse.

pstack upgrade keeps whichever mode the host is in, and the push password with it. Workers get the plugin from the join material; see Swarm mode.

control/loki/config.yaml is kept on init, upgrade and logging loki. pstack mounts control/loki in both modes, so pstack logging never recreates the pstack container.

The plugin is pinned to Loki’s version (grafana/loki-docker-driver:3.7.7-<arch>), and pstack upgrade never upgrades it. Doing it interrupts every preview on that node, because dockerd restarts. On each node, with <arch> set to amd64 or arm64:

Terminal window
$ docker plugin disable --force loki
$ docker plugin upgrade loki grafana/loki-docker-driver:<new>-<arch> --grant-all-permissions
$ docker plugin enable loki
$ sudo systemctl restart docker # rc-service docker restart on Alpine

On a host with pstack logging loki, the Control page has a Logging panel. Behind it:

Route Least role Body
GET /api/logging maintainer —
PUT /api/logging maintainer { retentionDays, chunks: { idlePeriodMinutes, maxAgeMinutes, targetSizeKiB, encoding } }
PUT /api/logging/storage admin { type: "filesystem" } or { type: "s3", endpoint, region, bucket, pathStyle, accessKeyId, secretAccessKey, cutover }
  • A save that changes something answers 202 { job }: a loki-apply job that restarts Loki. An unchanged save on an idle host answers 200 { "changed": false }.
  • Ranges and the earliest cutover come from GET /api/logging → limits.
  • S3 is one-way. Once saved, endpoint, region, bucket, pathStyle and cutover are fixed; only the keys change. cutover is the first UTC day on S3.
  • The secret is write-only. An empty, omitted or •••••••• secretAccessKey keeps the stored one.
  • The loki-apply transcript is viewer-readable and may name the endpoint and bucket in Loki’s error lines; only the secret and key id are scrubbed.
  • An S3 save first writes and deletes a pstack-probe-<hex> object. The probe runs from pstack’s networks, not Loki’s: an endpoint only Loki can reach fails after the cutover, not at save.
  • config.yaml is pstack’s: hand edits are reverted by the next save or pstack start. A live schema period is never dropped.
  • 409 Loki is not running on this host: run pstack logging loki. 409 Loki's config.yaml is missing or read-only: run pstack upgrade.
Terminal window
$ curl -s -X PUT https://api.preview.example.com/api/logging \
-H "authorization: Bearer $PSTACK_TOKEN" \
-d '{"retentionDays":14,"chunks":{"idlePeriodMinutes":30,"maxAgeMinutes":120,"targetSizeKiB":1536,"encoding":"snappy"}}'
{
"job": { "id": "loki-apply-pstack-control-3-…", "stack": "pstack-control", "action": "loki-apply", "state": "running" }
}
$ curl -s -X PUT https://api.preview.example.com/api/logging/storage \
-H "authorization: Bearer $PSTACK_TOKEN" \
-d '{"type":"s3","endpoint":"https://s3.eu-central-1.amazonaws.com","region":"eu-central-1","bucket":"pstack-logs","pathStyle":false,"accessKeyId":"AKIA…","secretAccessKey":"…","cutover":"2026-09-16"}'
{
"error": "S3 refused the probe: 403 InvalidAccessKeyId"
}
Terminal window
pstack api logging get
pstack api logging set --data '{"retentionDays":14,"chunks":{"idlePeriodMinutes":30,"maxAgeMinutes":120,"targetSizeKiB":1536,"encoding":"snappy"}}'

With --logging loki, Grafana runs at https://grafana.<domain>. Sign in with your pstack account. A visit without a Grafana session goes through pstack’s sign-in (password or SSO) and returns to the page you opened. A browser already signed in to pstack goes straight through.

pstack role Grafana
viewer 403 No Grafana access.
developer Editor
maintainer Editor
admin Admin
  • pstack’s sign-out is Grafana’s. Signing out, changing your password or losing the account ends Grafana access on the next request. A role change applies on the next request. Grafana has no sign-out menu.
  • Only a browser session. PSTACK_TOKEN and personal tokens are not Grafana access.
  • Log lines in Grafana are not redacted. Loki stores what containers printed, secrets included, and Grafana shows it as stored. Editors and Admins read it in Explore. That is why viewers are refused: pstack shows them redacted logs only. Developers and above can already open a shell in those containers.
  • No Grafana server admin. Plugin installs and server settings are unavailable in Grafana’s UI.
  • No live tail. Grafana Live is off, so nothing keeps streaming after a sign-out.
  • Logs Drilldown downloads from grafana.com on Grafana’s first start. Without that egress, Explore still works.
  • pstack logging off keeps Grafana’s volume. Turning logging back on restores users and preferences.
  • A username deleted and created again inherits the old Grafana user: its preferences, stars and the dashboards it owns.
  • Grafana down. grafana.<domain> shows Grafana is not running.
  • Nav link. Hearth and the advanced UI link to Grafana for developer and above; hidden with a stored token.
  • Logs links. In Hearth and the advanced UI, a deployment’s header links to Explore on the stack’s logs ({service_name=~"<stack>-(web|api)"}), down or asleep included: the services are the ones its compose declares (declaredServices on /runtime) plus any running. A service a later redeploy removed drops out of that link; its streams stay in Loki. Each service’s logs link to that service’s ({service_name="<stack>-<service>"}). Both cover the last hour. Same gate as the nav link; never on a share link. Swarm replicas share one stream, so the link is per service, not per container.

init — and upgrade — are CLI-only and will never be HTTP routes, because the API cannot recreate the stack that contains it: the process running the upgrade is inside the container being replaced, so it is killed mid-operation, the request never returns, the job transcript dies with the process (job history is in-memory), and a bad image leaves you with no control plane and no remote way back. The host keeps one capability the API doesn’t, and that asymmetry is the recovery path.

Practically: never submit a spec whose compose project is the one running Traefik and pstack. Nothing in the code can stop you — the API cannot reliably know its own deployment id.

The control stack has an operator page: Control stack in the UI (maintainer and up), or

Terminal window
pstack api host control-runtime
# → { containers: [ { service, image, state, health, restartCount, oomKilled,
# memLimitBytes, startedAt, … } ], reachable }

The two fields that earn the page are restartCount and oomKilled. A Traefik restart wipes its in-memory ACME challenge tokens, so certificate issuance silently fails mid-flight while every container still reports running — a climbing restart count with oomKilled: true is that whole story in two fields. (GET /api/control remains the viewer-rank summary the dashboard uses.)

One action, one refusal:

Terminal window
pstack api host control-restart --service traefik # severs connections for a few seconds
pstack api host control-restart --service pstack # 400 — always

The server refuses to restart its own container, whoever asks — root included. Recreating the container answering the request kills the request (and any running job) with it, which is the same reason init is CLI-only. From the host: docker compose -p pstack-control restart pstack.

Hostname Serves
control.<domain> the web UI (an operator’s browser)
api.<domain> the API (CI, curl, scripts)
loki.<domain> Loki’s push endpoint, for the nodes’ log plugins (--logging loki); reserved even with logging off
grafana.<domain> Grafana (--logging loki), signed in with pstack accounts; reserved even with logging off
<service-name>.<domain> the convention for a shared service’s own hostname
<surface>-pr-<n>.<domain> a per-PR surface, e.g. backend-pr-123.<domain>
<surface>-<route>.<domain> the same surface through a custom route, e.g. backend-checkout.<domain>

control and api are two routers pointing at one container — the API process serves the UI. The UI calls the API with relative /api/… paths, so it is same-origin from control.<domain> and needs no CORS; api.<domain> exists to give external callers an honest name that is not “the UI host”.

A pstack.routing.host naming control., api., loki. or grafana. on any domain this host answers on is refused at deploy.

Flatten per-PR hostnames with dashes. A wildcard matches exactly one label: backend-pr-1.<domain> is covered by *.<domain>, backend.pr-1.<domain> is not.

Custom routes: a stable name for a moving stack

Section titled “Custom routes: a stable name for a moving stack”

A preview’s hostname carries its stack name, so it changes with every PR: web-myapp-pr-123.<domain> today, web-myapp-pr-124.<domain> tomorrow, and every link you shared breaks. A custom route is a name you point at a deployment. Route checkout assigned to the deployment whose stack is myapp-pr-123 makes every host that stack serves answer on a twin with the route in place of the stack name:

Stack host Route host
web-myapp-pr-123.preview.example.com web-checkout.preview.example.com
api-myapp-pr-123.preview.example.com api-checkout.preview.example.com
wildcard *.web-myapp-pr-123.preview.example.com *.web-checkout.preview.example.com

Point it at the next PR and the same links follow. No redeploy: pstack rewrites one Traefik file, pstack-routes.yml, and Traefik picks it up in about two seconds.

  • Which hosts get a twin. Every service autolabel routes as <service>-<stack>.<domain>, and each wildcard subdomain derived from one. A service with an explicit pstack.routing.host, an explicit subdomains host, or its own traefik.* labels has a host that does not carry the stack name, so it already is stable and gets no twin.
  • Subdomains on the route. PUT /api/custom-routes/{name}/subdomains { depth } (one, any or null; the Subdomains select in both UIs) gives the route *.<host> for every host it mirrors that has no wildcard from its stack, with no redeploy. It belongs to the route, so it follows the route to the next stack. A wildcard something else serves is a 409. Each row of GET /api/custom-routes carries subdomains.
  • Certificates. A route host inherits the host’s certificate. A wildcard twin follows the subdomain rules: on dns01 each route and subdomain service orders one certificate for web-checkout.<domain> + *.web-checkout.<domain>, and moving the route to another stack reuses it.
  • Names. A DNS label of at most 40 characters (a-z, 0-9, -): anything else is a 400. control, api, loki and grafana are reserved (400). The stack name of a registered deployment, or a route that exists, is a 409.
  • One owner at a time. Assigning a route that another deployment holds is a 409 naming it, checkout is assigned to myapp-pr-122, with assignedTo: { deployment, stack } in the body. Send force: true (--force) to move it: one call, one rewrite, one route.assigned event carrying previous. Assigning it to the deployment that already holds it is a 200 that changes nothing.
  • No two routers for one host. An assign is refused (409, naming the host or the router) when a route host is already served by another deployment or route. A collision that comes later (a deploy that claims a route host, a stack named like a route) is settled at every render, never left to Traefik: a deployment’s own host always wins, and between two routes the one assigned first wins. The route stops serving that one host, keeps its others, and lists it under blocked. When the winner goes (unassigned, deleted, or redeployed without the host), the route serves it again.
  • Asleep is fine. A route may point at a sleeping or not-yet-deployed deployment: it stores the intent. A request to a route host wakes a sleeping stack exactly like its own host does.
  • Forgetting a deployment unassigns its routes (DELETE /api/deployments/:id, or down with forget). The routes stay, unassigned, and serve nothing until you point them somewhere.
  • pstack-routes.yml is pstack’s file. It is rendered from the custom_routes table, so the routing API refuses to write or delete it, and a config export carries neither the table nor the file.

In the UI (Hearth and the advanced one; the basic UI has none): Routing lists every route with its hosts and stack, and creates, assigns, unassigns and deletes them; a deployment’s page shows the routes pointing at it, with their hosts as links. Moving a held route asks first: “Move checkout from myapp-pr-122 to myapp-pr-123?”. Reading takes viewer; every write takes developer (7e).

The API:

Terminal window
curl -s -X POST "$PSTACK_API_URL/api/custom-routes" -H "authorization: Bearer $PSTACK_TOKEN" \
-d '{"name":"checkout","deployment":"pr-123"}'
# → 201 { name: "checkout", deployment: "pr-123", stack: "myapp-pr-123",
# hosts: ["web-checkout.preview.example.com", "api-checkout.preview.example.com"], blocked: [],
# createdAt, updatedAt }
curl -s -X PUT "$PSTACK_API_URL/api/custom-routes/checkout/assignment" -H "authorization: Bearer $PSTACK_TOKEN" \
-d '{"deployment":"pr-124","force":true}'

hosts lists what the route serves now: the plain hosts, then each wildcard as *.<host>. blocked lists each host it does not serve because something else does, as { host, by: { kind, name } }: kind deployment (name is its stack) or route. The UIs show a blocked host as text, “taken by ”, never as a link. deployment and stack are null while it is unassigned. The generated pstack api custom-routes list|create|delete|assign|unassign reaches the same five routes (pstack api custom-routes assign --name checkout --deployment pr-124 --force).

The same thing from a terminal. It talks to PSTACK_API_URL as PSTACK_TOKEN (the host’s token, or a personal one at developer to write), like pstack api:

Terminal window
$ pstack route create checkout pr-123
checkout myapp-pr-123 web-checkout.preview.example.com, api-checkout.preview.example.com
$ pstack route assign checkout pr-124
pstack: checkout is assigned to myapp-pr-123 (--force moves it)
$ pstack route assign checkout pr-124 --force
checkout myapp-pr-124 web-checkout.preview.example.com, api-checkout.preview.example.com
$ pstack route create staging
staging (unassigned)
$ pstack route ls
checkout myapp-pr-124 web-checkout.preview.example.com, api-checkout.preview.example.com
staging (unassigned)
$ pstack route ls # after stack shop claimed web-checkout.preview.example.com
checkout myapp-pr-124 api-checkout.preview.example.com
blocked: web-checkout.preview.example.com (deployment shop)
$ pstack route unassign checkout
checkout (unassigned)
$ pstack route rm staging
staging deleted
Command Does
pstack route ls every route: name, stack, hosts, and a blocked: line per host something else serves
pstack route create <name> [<deployment>] a new route, assigned when a deployment is given
pstack route assign <name> <deployment> [--force] point it at a deployment; --force moves it from another
pstack route unassign <name> stop serving it; the route is kept
pstack route rm <name> delete it

--json prints the API’s body instead. A refusal exits 1 with the server’s sentence; bad usage exits 3.

Two of the three modes get certificates from Let’s Encrypt through Traefik’s le resolver, and differ in what proves you own the domain — which decides how many PRs a week the host can certify. The third, dns-persist-01, takes Traefik out of issuance entirely: you supply the wildcard and the host serves it.

--challenge http01 (default) --challenge dns01
Credential none a DNS API token to obtain, store and rotate
Hard requirement port 80 reachable from the internet the provider’s API reachable
Traefik flags httpchallenge=true, httpchallenge.entrypoint=web dnschallenge=true, dnschallenge.provider=<code>
Wildcards cannot issue them — one certificate per hostname one *.<domain> covers every present and future host
New-cert budget ~50/week per registered domain ⇒ ~16 PRs/week at 3 surfaces each one certificate, so no per-PR issuance and no ceiling
URL valid before deploy no — the hostname must already have a container answering yes — the wildcard exists before the stack does
Per-PR router labels tls=true and tls.certresolver=le tls=true and nothing else

The redirect is not a problem for HTTP-01. The control stack redirects web → websecure, and Traefik still answers the challenge: it installs an internal ACME router at maximum priority that bypasses the redirect for /.well-known/acme-challenge/. The one thing that does break HTTP-01 is port 80 not being reachable from the internet.

The arithmetic that makes you move to DNS-01

Section titled “The arithmetic that makes you move to DNS-01”

Let’s Encrypt allows roughly 50 new certificates per registered domain per week. Renewals do not count against it; a separate duplicate-certificate limit caps 5 identical certificates per week. HTTP-01 cannot issue a wildcard, so every hostname is a new certificate:

3 surfaces per PR (backend, frontend, admin) × 1 certificate each = 3 new certs per PR
50 new certs per week ÷ 3 ≈ 16 new PRs per week

Past that, issuance starts failing and the symptom is a browser TLS error on a preview that deployed fine. There is no way to raise it and no way to make HTTP-01 issue one certificate for many hosts — the only fix is DNS-01. The second reason to move: HTTP-01 cannot certify a hostname before its container exists, so a preview URL is invalid until the stack is actually deployed, which surfaces as a certificate error that is really a sequencing problem. DNS-01’s wildcard is valid immediately.

Start on http01; switch with --challenge dns01 --dns-provider <code> when PR volume or pre-deploy URLs demand it. Re-running init is the whole migration.

The per-PR certresolver rule is OPPOSITE per mode

Section titled “The per-PR certresolver rule is OPPOSITE per mode”

This is the easiest thing in the whole system to get wrong, and it is expensive in one direction.

Mode Every per-PR router Why
http01 tls=true + tls.certresolver=le there is no wildcard to inherit; each hostname must resolve its own certificate, ordered the moment its router loads. Omit the resolver and that host has no certificate, ever
dns01 tls=true — nothing else exactly one always-on router requests the wildcard (tls.domains[0].main=<domain> + .sans=*.<domain>, on the control router). Every other router inherits it by SNI
dns-persist-01 tls=true — nothing else same rule as dns01, different source: the wildcard is a certificate you supplied (PUT /api/tls/wildcard), served from Traefik’s certificate store. Nothing on the host orders anything

Under DNS-01, adding tls.certresolver=le to a per-PR router orders a SEPARATE certificate for that hostname — which is how a fleet of previews silently burns the ~50-per-week budget and takes TLS down for the whole host, including the control plane. Copying a router label block from an HTTP-01 host into a DNS-01 host is exactly how it happens.

Provider codes and variable names are lego’s, and only the verified ones are written for you. A wrong variable name surfaces as an ACME “propagation timeout”, which sends you debugging DNS instead of a typo — so an unrecognised provider gets a CHANGEME_VARIABLE_NAME line pointing at lego’s provider list rather than a guess.

Provider --dns-provider Credential in dns.env
Cloudflare cloudflare CF_DNS_API_TOKEN — one token with Zone:Read + DNS:Edit
Hetzner hetzner HETZNER_API_TOKEN (optionally HETZNER_PROPAGATION_TIMEOUT, HETZNER_TTL)
AWS Route 53 route53 none — satisfied by the instance’s IAM profile
Google Cloud DNS gcloud none — satisfied by the VM’s attached service account

Every lego variable also accepts a _FILE suffix if you would rather mount the secret than store it. It is HETZNER_API_TOKEN — never HETZNER_API_KEY, which does not exist and fails as a propagation timeout. Prefer the tokenless providers where you have the choice: nothing to store, nothing to rotate.

Point a wildcard at the box so any per-PR hostname resolves:

*.preview.example.com. A <host-ip>
preview.example.com. A <host-ip>

Under DNS-01 that wildcard record plus the apex is also what the single wildcard certificate covers. Under HTTP-01 you still want the wildcard record — resolution and certification are separate problems — but each hostname is certified individually, the moment its router loads at deploy.

A host answers on the domain init gave it. GET/PUT /api/domains adds more — for a migration you can perform gradually rather than in one cutover:

Terminal window
pstack api tls domains # what it answers on now
pstack api tls domains-set --data '{"domains":["preview.new-company.com"]}'

(Or the Domains panel on the Control stack page.) Each added domain gets control.<d>, api.<d> and a wake catch-all written into Traefik’s watched directory — live in about two seconds, with no re-init, no restart and no downtime. The list is the file: GET /api/domains reads it back out of the routers it wrote, so the two cannot disagree.

Standing a host up on a domain that is not yours yet. init and cloud-init take --extra-domain <host> (repeatable), which registers the domain from the first boot:

Terminal window
pstack init --domain preview.new-company.com --acme-email ops@example.com \
--extra-domain preview-temp.example.com

The case it exists for is a cutover. preview.new-company.com is still pointing at the old box, so nothing under it resolves here yet — but its routers exist from the moment init runs, so when you move the DNS record it simply starts working, with no pstack change at all. Meanwhile preview-temp.example.com is usable. Afterwards, drop the temporary one from the Domains panel or with a PUT; nothing else needs touching.

--extra-domain only ever adds. Re-running init merges into whatever /api/domains already holds, so a domain someone added through the UI is never removed by an upgrade.

Each added domain’s control. serves whatever console this host runs — the advanced SPA when it has one, the embedded UI otherwise — detected from the running control stack rather than stored, so pstack ui advanced heals existing domains when the control plane restarts. api. and the wake catch-all always point at the API container, whatever the console serves.

The primary domain is not in that list and cannot be removed from it. Its routers are labels on the pstack container, deliberately: whatever goes wrong in a dynamic file, the hostname you would use to undo it still answers. That is also why this is a file rather than more labels — a label cannot be added to a running container, so doing it that way would mean recreating the container serving the request.

Adding a domain does not move anything. It makes the host able to serve and wake names under it. A preview’s hostname comes from its own spec, so you move one deployment by setting PREVIEW_DOMAIN in its variables and redeploying it — the unit of migration is one stack, and rolling back is that same stack. Deployments you have not touched keep the domain they were deployed under.

Don’t forget the certificates, since the rule differs per mode:

Mode An added domain…
http01 gets its own per-hostname certificates automatically — and its own weekly budget, since Let’s Encrypt counts per registered domain. Port 80 must reach the box for that name too
dns01 pins its own wildcard, so one domain failing validation cannot take another’s certificate down. The DNS credential must be able to serve that zone as well
dns-persist-01 must be covered by the stored pair — PUT /api/tls/wildcard refuses one whose SANs miss a registered domain, rather than letting it fail in a visitor’s browser

Bring your own wildcard: dns-persist-01 (0.35.0)

Section titled “Bring your own wildcard: dns-persist-01 (0.35.0)”

The third mode needs no re-init, no Traefik restart, and no DNS credential on the host: you obtain a wildcard certificate yourself (certbot with a manual DNS record, your company’s CA, however you like) and hand the pair to the API. It lands beside Traefik’s dynamic config, every preview inherits it by SNI, and per-PR certificate orders stop entirely — which is the whole rate-limit problem gone, and nothing left in Traefik’s memory for a restart to lose.

Terminal window
# PIPED, never -d "$(…)": a private key in argv is readable by every local user in `ps` and
# lands in your shell history.
jq -n --rawfile cert fullchain.pem --rawfile key privkey.pem '{cert: $cert, key: $key}' \
| curl -sX PUT https://api.preview.example.com/api/tls/wildcard \
-H "authorization: Bearer $PSTACK_TOKEN" -H 'content-type: application/json' --data-binary @-
curl -sX POST https://api.preview.example.com/api/tls/redeploy \
-H "authorization: Bearer $PSTACK_TOKEN"

Through the CLI (same caveat — the key would be an argument, so prefer the piped form above for the store; the other three are safe):

Terminal window
pstack api tls status
pstack api tls redeploy
pstack api tls wildcard-remove

(Or the Control stack page in the UI, which also shows days-to-expiry.) The PUT validates the pair — match, dates, that it actually covers *.<domain> — and refuses with the reason otherwise. The redeploy is the step people miss in every mode switch: router labels are stamped at deploy time, so stacks deployed before the wildcard keep ordering their own certificates until they deploy once more. Asleep stacks are skipped — their labels regenerate on wake.

tls-wildcard.yml in Traefik’s dynamic directory is pstack’s file, not yours: the routing API refuses to write or delete that one name (whoever asks), because its presence is the mode and the certificate pair it names lives beside it. It also does not travel in a config export — the pair cannot, so the pointer must not either, or the target host would enter the mode with nothing to serve. pstack-domains.yml and pstack-routes.yml are pstack’s too, and refused the same way: they are rendered from the domain list and from the custom routes.

What this mode does not do yet: renew. The certificate is a static file; the UI shows a red badge under 21 days and renewing is PUT again with the fresh pair. GET /api/tls reports the mode and the certificate’s public facts; the private key has no read path, ever. Exact-SAN certificates already in acme.json keep winning the handshake for their own hostnames, so adopting this mode revokes nothing.

Leaving it is DELETE /api/tls/wildcard — then redeploy again, for the mirror-image reason: the stacks are carrying tls=true alone and need their resolver back.

kind is the second field in a spec and it decides how the deployment may be treated:

kind: isolated (default) kind: shared
What one tenant — normally one PR a host singleton every preview borrows: a database, a queue cluster, a registry mirror
Axes yes — the point of the tool none allowed; declaring one is a hard error
down routine refused without --force
Over the API down works refused with 409 unless the body says { "force": true }
version: 1
kind: shared
stack: shared-db # a fixed identity, not a template — there is only one per host
compose:
file: docker-compose.shared.yml
profiles: [] # nothing is profiled: a shared stack is always fully on
Terminal window
$ pstack -f shared.yml validate
stack: shared-db
✓ spec parses — kind: shared, 0 axis/axes, stack "shared-db"
compose: docker-compose.shared.yml [no profiles]

Axes on a shared deployment are rejected at parse time, not warned about — it is almost always a spec that meant isolated:

Terminal window
$ pstack -f axes-on-shared.yml validate
pstack: kind: shared cannot declare axes (found 1). Axes exist to isolate one tenant from another and to prove a tenant's resources were cleaned up; a shared singleton has neither concern. Did you mean `kind: isolated`?
$ echo $?
3

down runs docker compose down -v. On a PR stack the -v removes that tenant’s own volumes — routine. On a shared deployment the same verb removes Traefik’s acme.json (every certificate for the host, re-issued under a per-week rate limit), the shared database volume (every preview’s state), and your admin credentials. Same command, entirely different blast radius:

Terminal window
$ pstack -f shared.yml down
stack: shared-db
refusing to tear down shared deployment "shared-db"
✗ compose shared-db — refused: kind is `shared`. `down` removes volumes (-v), which on a shared deployment destroys state every tenant depends on. Re-run with --force if that is truly intended.
$ echo $?
1

--force lifts it, and nothing else does — over HTTP that is { "force": true } in the POST /api/deployments/:id/down body, and without it the API answers 409 synchronously rather than handing back a job id that is going to fail. Reach for it only when destroying that state is the actual goal; to upgrade a shared deployment, run up — it converges and never removes:

Terminal window
$ pstack -f shared.yml down --force --dry-run
stack: shared-db (dry-run)
→ compose down (all profiles)
[dry-run] compose down
→ verify (asserting resources are gone)
✓ compose (compose)
$ echo $?
0

Note the guard keys off the declared kind, not off “does it have axes”. An isolated deployment that forgot its axes must not silently inherit a singleton’s protection — which is exactly why the no-axes warning in section 2 tells you to consider kind: shared.

requires: — fail by name, before anything is created

Section titled “requires: — fail by name, before anything is created”

An isolated deployment usually depends on shared ones: an ingress network, a reachable queue, a database endpoint. Without a preflight, a missing dependency surfaces partway through an axis hook as whatever error that CLI printed — which tells you nothing about what is actually wrong, after some resources already exist.

requires:
- name: shared-db
assert: docker network inspect preview-shared >/dev/null 2>&1
hint: bring the shared deployment up first — `pstack -f shared.yml up`

validate lists them; up asserts every one before the first axis runs:

Terminal window
$ PR=123 pstack -f req.yml validate
stack: pr-123
✓ spec parses — kind: isolated, 1 axis/axes, stack "pr-123"
requires: shared-db
compose: docker-compose.preview.yml [backend]
- database: up, down, assert_gone
Terminal window
$ PR=123 pstack -f req.yml up
stack: pr-123
→ requires: shared-db
✗ requires shared-db — unmet — bring the shared deployment up first — `pstack -f shared.yml up`
$ echo $?
1

Nothing was provisioned. Write the hint as how to fix it — the assert already says what broke. Requirements are asserted in declaration order and the first failure stops the run.

The API is registry-backed: it holds many deployments under $PSTACK_DATA/deployments/<id>/ (default /var/lib/pstack) and acts on them by id.

/var/lib/pstack/deployments/pr-123/
spec.yml the submitted spec
compose.yml the submitted compose file, when one was sent with it
meta.json { id, kind, createdAt, updatedAt }

Plain files on purpose: the registry is a cache of intent, never the source of truth about what exists — truth stays in Docker and in each axis’s assert_* probe. Losing it means “I forgot what you asked for”, not “the host is inconsistent”, and the fix is to re-submit. It is also greppable, diffable and tar-able, which a database is not.

Terminal window
API=https://api.preview.example.com
# submit or replace → 201 new, 200 replaced
curl -sS -X PUT -H "Authorization: Bearer $PSTACK_TOKEN" \
-H 'content-type: application/json' \
-d "$(jq -n --rawfile s preview.yml --rawfile c docker-compose.preview.yml \
'{spec:$s, compose:$c, env:{PR:"123"}}')" \
"$API/api/deployments/pr-123"
curl -sS "$API/api/deployments" # list, with busy + running
curl -sS "$API/api/deployments/pr-123?PR=123" # meta + spec summary
curl -sS -X POST -H "Authorization: Bearer $PSTACK_TOKEN" \
"$API/api/deployments/pr-123/up?PR=123" # → 202 { job }
curl -sS -X DELETE -H "Authorization: Bearer $PSTACK_TOKEN" \
"$API/api/deployments/pr-123?PR=123" # forget, after a clean down
curl -sS -X POST -H "Authorization: Bearer $PSTACK_TOKEN" -d '{"forget":true}' \
"$API/api/deployments/pr-123/down?PR=123" # both, in one job: tear down, forget if clean

Under swarm, the PUT tells you what the conversion will change (0.30.0). The response carries swarmNotes, produced by the same conversion the deploy runs, so a submission and the job log can never name different keys:

{
"id": "pr-123", "kind": "isolated", "stack": "pr-123",
"swarmNotes": [
"swarm: service api: depends_on: dropped — swarm has no start-order dependency; wait in the container's own entrypoint",
"swarm: service api: restart: always → deploy.restart_policy.condition: any"
]
}

They name what you wrote, not the routing labels pstack generates, because those are the ones you can act on — so up’s own list may be longer. Absent, never [], when nothing was checked: under compose there is no conversion, and a compose file that does not parse is reported far better by up than by a guess here. They are advisory — a submission is never rejected for them.

Five things that will bite you if you skip them:

  • Variables ride on the query string, and are not stored. A spec resolving stack: pr-${PR} needs ?PR=123 on every call — GET, up, and the later down. Pass different ones to down than you did to up and teardown targets a different stack than deploy created. A missing variable is a 400 naming it, never a stack called pr-.
  • PUT is refused (409) while that stack has a job in flight. Swapping the spec mid-job means the eventual down runs with different profiles and axes than up created.
  • DELETE fails closed. It refuses while containers exist, and refuses when Docker did not answer — “could not tell” is not evidence of absence. Forgetting a live deployment orphans it beyond the control plane’s view, which is exactly the leak this tool exists to prevent. Always down first.
  • Submitted hooks cannot use relative paths. A deployment’s runner runs with cwd set to its own directory (so compose: { file: compose.yml } finds the file PUT wrote), and only spec.yml and compose.yml live there. up: ./hooks/db.sh … works from a CLI checkout and cannot work over the API — use inline shell or absolute paths.
  • :id is a registry id, not a compose project name. The server owns the stored spec and resolves stack: itself, so a client can never ask it to act on an arbitrary compose project.

There is no importable library: the binary is the product, and the programmatic surface is the HTTP API — @samyx/preview-stacks-client from TypeScript, or any HTTP client. Ids must match /^[a-z0-9][a-z0-9._-]{0,63}$/ — they become directory names and reach shell hooks, so no traversal, no spaces, no metacharacters.

For CI, prefer the CLI with -f and --set (section 8): it needs no host access and no token.