Skip to content

7b. Scale out, sleep, and share (0.26.0)

Three things a preview host grows into once it has more than a handful of PRs on it: a second machine, previews that cost nothing while nobody looks at them, and a way to show one person one stack’s logs without making them an account.

Previews deploy one of two ways. It is a host-level decision with a per-deployment escape hatch, and nothing about the spec you write changes between them.

swarm (the default since 0.26.0) compose
Deploys with docker stack deploy, converting the compose file on every deploy docker compose up -d, byte for byte what you submitted
Networks overlay --attachable bridge
More than one machine yes — that is the whole point no, one box
mem_limit, privileged, devices, depends_on, profiles dropped or converted, and named in the notes work as written
docker exec, container start/stop, the terminal manager-local; a task on a worker is listed and reachable for logs, not for a shell always available
Volumes on teardown removed on the manager; one a task created on a worker stays there removed

Choose compose when the host will only ever be one machine and a service needs something swarm cannot express. Choose swarm — or just take the default — if a second machine is plausible: it costs nothing on one node, and adding a worker later is one command rather than a rebuild.

Three places set it, most specific first:

compose:
file: docker-compose.yml
orchestrator: compose # 1. this deployment only
  1. PSTACK_ORCHESTRATOR on the server — what pstack init --orchestrator writes into control/.env, and the host default every deployment inherits.
  2. Neither: compose. A spec run straight from the CLI on a laptop is not secretly a swarm.

Switching an existing host is pstack init --orchestrator <the other one> on the host — the same idempotent command that stood it up. One precondition, and it is not a soft one: the two networks change driver (bridge ↔ overlay), and a driver swap is only possible when nothing but the control stack is attached. Tear every preview down first. A preview still attached is a hard stop that names the network rather than a half-migrated host. pstack upgrade never changes the mode — it keeps whatever the host already has.

GET /api/swarm answers which mode is live: active: false means previews run with compose, and reachable: false means docker did not answer at all — which is not the same as “no nodes”.

A new host stood up with pstack init is a one-node Docker Swarm manager, and previews deploy as swarm stacks. You will not notice until you need a second box — then it is one command on the new machine (below) and previews start landing on it.

You write plain compose. docker stack deploy reads the compose v3 schema strictly — mem_limit, cpus, profiles and pull_policy are hard errors, restart: is silently ignored and swarm’s own default (any) would loop a one-shot migration container forever. pstack converts the submitted file on every deploy and names what it changed in the job log (swarm: service app: restart: always → deploy.restart_policy.condition: any). The file in the registry is never modified.

In the file you submit In the stack that deploys
profiles: services behind a profile the spec does not select are left out; --prune removes a service that was in last time (the --remove-orphans equivalent)
restart: always / unless-stopped deploy.restart_policy.condition: any
restart: on-failure[:N] condition: on-failure (+ max_attempts: N)
no restart: / restart: no condition: none — what compose does; not swarm’s default
mem_limit, cpus, pids_limit, mem_reservation deploy.resources.limits.memory / .cpus / .pids, reservations.memory
labels: traefik.* moved to deploy.labels (the swarm provider reads service labels); traefik.docker.network → traefik.swarm.network
build, container_name, privileged, devices, network_mode, depends_on dropped, with a note saying why and what to do instead
any key outside the v3 schema (pull_policy, platform, extends, …) dropped, with a note
top-level name:, version: "2.x" dropped
a deploy: block you wrote yourself kept; only missing keys are inferred

A service that genuinely cannot run under swarm (privileged, a device mount) can stay on compose on the manager: set compose.orchestrator: compose in that spec. The host default comes from PSTACK_ORCHESTRATOR, which init writes into the control stack.

compose:
file: docker-compose.yml
orchestrator: compose # this one deployment only; everything else follows the host

Three ceilings, stated rather than hidden:

  • docker stack rm never removes volumes. Teardown removes the stack’s labelled volumes on the manager; a volume a task created on a worker stays there. Use named volumes only for data you can lose, and an axis (with its assert_gone) for data you cannot.
  • docker exec, stop, start are node-local. A task on a worker is listed on the Containers tab (with its node, marked remote), logs reach it through the manager, but the terminal and the per-container buttons refuse it with a 409 that names the node.
  • A relative bind mount (./data:/data) resolves against the compose file’s directory on each node. It works on the manager and fails on a worker that has no such directory.

Adding a worker. Open the ports first, between the new machine and every other node:

Port For
2377/tcp cluster management (worker → manager)
7946/tcp+udp node discovery (every node ↔ every node)
4789/udp overlay network traffic, VXLAN (every node ↔ every node)

Then take the join material — from the host with pstack swarm join, from the Swarm page (Add a worker → Reveal), or from the API — in whichever shape the new machine wants.

On the host, over SSH:

Terminal window
pstack swarm # the node table, the manager address, the ports
pstack swarm join # → docker swarm join --token SWMTKN-1-… 203.0.113.10:2377
pstack swarm join --format script > join.sh
pstack swarm join --format cloud-config --distro debian -o worker.yaml
pstack swarm previews workers # this manager keeps only the control stack
pstack swarm previews any # and back

pstack swarm exits 1 when this host is not a manager (or docker did not answer), so a script can ask without parsing the table. The join material goes to stdout and everything else to stderr, so pstack swarm join --format token pipes cleanly.

Or over the API, from anywhere:

Terminal window
# one line, for a machine that already runs Docker
curl -s https://api.preview.example.com/api/swarm/join?format=command -H "Authorization: Bearer $PSTACK_TOKEN"
# → docker swarm join --token SWMTKN-1-… 203.0.113.10:2377
# a script that installs Docker (get.docker.com) if missing, then joins
curl -s "…/api/swarm/join?format=script" -H "Authorization: Bearer $PSTACK_TOKEN" > join.sh
# cloud-init user-data for a fresh machine: Docker from the distro's repositories, then join
curl -s "…/api/swarm/join?format=cloud-config&distro=debian" -H "Authorization: Bearer $PSTACK_TOKEN" > worker.yaml
hcloud server create --name worker-1 --image debian-12 --user-data-from-file worker.yaml

With Loki logging on (pstack init --logging loki), script and cloud-config install the loki log plugin after Docker and before the join. A failed install never blocks the join: swarm keeps logged services off that node. Run the script again on a worker that joined earlier to give it the plugin.

The token is a secret: whoever holds it can add a node that runs any task on the cluster. The route is admin-only, the Swarm page fetches it only when you click Reveal and forgets it when you leave, and docker swarm join-token --rotate worker on the manager invalidates it. GET /api/swarm (the polled view) never carries it.

Terminal window
curl -s https://api.preview.example.com/api/swarm -H "Authorization: Bearer $PSTACK_TOKEN"
{ "reachable": true, "active": true, "nodeId": "n1…", "managerAddr": "203.0.113.10:2377",
"nodes": [ { "id": "n1…", "hostname": "preview-host", "role": "manager", "status": "ready",
"availability": "active", "managerStatus": "leader", "engineVersion": "28.0.1", "self": true,
"lokiPlugin": null } ],
"ports": [ … ], "note": "…" }

reachable: false means docker did not answer — nothing is known, which is not “no nodes”. active: false means the host runs previews with compose; pstack init --orchestrator swarm (on the host, with every preview torn down first — the networks have to be recreated) switches it.

lokiPlugin: false means the node has no loki log plugin, so swarm keeps logged services off it. null means not checked (this host’s logging is off, or docker did not answer). lokiPluginInstall — the line that installs the plugin — is present only when logging is on. The Swarm page and pstack swarm flag the same nodes.

A swarm task in New has been created but never given an address or a machine. That normally lasts under a second. One that stays is waiting on swarm’s address allocator — in practice, a network with no addresses left — and swarm writes the reason only to the manager’s docker log, never to docker service ps. Since 0.41.0 the deploy’s readiness watch fails it after a minute and says so, and GET /api/signals lists it under stuck with the same sentence.

Confirm on the manager:

Terminal window
journalctl -u docker --since "1 hour ago" --no-pager | grep "available IP"

Output means the network is full. systemctl restart docker on the manager clears it for now (every preview URL and the control panel blink for 10–30 seconds), and a bigger network stops it coming back:

Terminal window
# every preview on the network asleep or down first — init names any still attached and stops
PSTACK_INGRESS_SUBNET=10.250.0.0/16 pstack upgrade

New hosts get that range already. The whole story, including what does not help: preview-ingress-address-leak.md.

Adding and removing worker machines (0.41.0)

Section titled “Adding and removing worker machines (0.41.0)”

Sleep frees a machine’s worth of capacity that nobody turns off, and a busy afternoon needs a machine nobody adds. pstack itself does not create or delete machines — but it is the only thing that can say when one is needed or spare, so it says it and leaves the rest to you, or to the optional worker scaler, which acts on these signals.

Terminal window
curl -s -H "Authorization: Bearer $PSTACK_TOKEN" https://api.<domain>/api/signals | jq
{
"v": 1, "swarm": true, "reachable": true, "at": 1758358800000,
"nodes": [
{ "id": "xk3f…", "hostname": "worker-3", "role": "worker", "state": "ready",
"availability": "active", "tasks": 0, "emptySince": 1758357000000 }
],
"stuck": [
{ "task": "j8d2…", "service": "pr-42_web", "stack": "pr-42",
"reason": "no suitable node (insufficient resources on 2 nodes)" }
]
}

stuck is “I need another machine”. Every task docker refused to place, with docker’s own sentence. Read it before you buy anything: insufficient resources means the cluster is full, while scheduling constraints not satisfied usually means a spec is asking for a machine nobody has. A task that starts never allocated is the opposite case — it is stuck in New and no machine will help (above).

A worker with tasks: 0 is “you can take this away”. emptySince is when pstack first saw it that way; how long you wait before acting is your policy, not pstack’s. The manager never appears as a candidate: it runs pstack itself, and your axis hooks run beside it. Tasks of global services (one per machine, like a log shipper) do not count — they follow the machine.

Rather be told than ask: signal.raised and signal.cleared fire on the change and carry the same fields (webhook-events.md). PSTACK_SIGNALS_TICK_MS sets how often pstack looks (default 30000; 0 turns it off).

A manager that also runs previews shares its memory with the swarm’s own bookkeeping, and a burst of previews starting at once can starve the manager until it stops answering. workers labels the manager pstack.previews=off, and every preview pstack deploys carries the placement constraint node.labels.pstack.previews != off: swarm moves running previews to a worker and places none there again. The control stack (Traefik, pstack, the UI, Loki, Grafana) keeps running, because it is plain compose. It is a label, not a drain: a drained node cannot attach plain containers to the overlay network, so the control stack would not start again. A preview deployed before 0.46.0 has no constraint until its next up.

Terminal window
pstack swarm previews workers # on the manager; same as the Swarm page's "Run previews on"
pstack init … --previews-on workers # at install time; cloud-init takes the same flag

Add a worker first. With none ready, the previews are pending, not running; the command, init and the Swarm page all say so. any labels the manager back on. The label is swarm’s own state, so it survives a restart and pstack upgrade leaves it alone. Over the API: POST /api/swarm/previews/workers (or /any), and GET /api/swarm reports previewsOn.

The daemon is protected too. pstack init (so cloud-init and upgrade) sets dockerd’s OOMScoreAdjust to -900 through a systemd drop-in, /etc/systemd/system/docker.service.d/pstack-oom.conf, and applies it to the running daemon through /proc, so there is no restart. On a host that runs out of memory the kernel kills the process with the biggest score, and dockerd is usually the biggest there; with the adjustment it takes a preview’s process first. Traefik and pstack carry oom_score_adj: -500 in the control stack for the same reason. Without root or systemd, init says so and carries on. It lowers who is killed first; it does not prevent running out of memory — draining the manager does that.

Taking a machine out of service, in this order:

Terminal window
H="Authorization: Bearer $PSTACK_TOKEN" # maintainer and up
curl -X POST -H "$H" https://api.<domain>/api/swarm/nodes/<id>/drain # swarm stops placing work there
# … now delete the machine at your provider …
curl -X DELETE -H "$H" https://api.<domain>/api/swarm/nodes/<id> # forget the node

Drain first, always. Swarm prefers the emptiest machine, so an idle worker is exactly where the next deploy would land while you are deciding. POST …/undrain puts it back if the delete never happens. The DELETE is refused with a 409 until docker reports the node down — a node that briefly loses the network still holds everything it was running, and removing it then orphans that work.

Two things to know before you wire this to anything that spends money:

  • A worker’s disks go with the machine. Anything a preview stored on it is gone. Under swarm that is already shaky — a stack that sleeps and wakes can come back on another machine with an empty volume — so treat preview data as disposable.
  • “Empty” means no swarm tasks. A manager cannot see plain containers on a worker, so a box somebody is using by hand looks idle.

Most previews are deployed to be looked at once, then sit there until the PR merges. Sleep takes the compose project down and keeps its volumes and every axis — the database branch, the seeded data, the images. The next request to any of its hostnames, or to a custom route host pointing at it, brings it back: the visitor sees “Your preview is spinning up…” for the length of a deploy, and then the app.

Declare it in the spec:

sleep:
idle: 2h # no request reached any of its routers for 2 hours
after: 3d # 3 days after the last deploy, whether anyone looked or not

Either, both, or neither. Durations are 90s, 30m, 2h, 3d, 1h30m. A spec without a sleep: block is never put to sleep by the scheduler. A node short of memory or cpu can still sleep it (Node pressure).

  • idle reads Traefik’s per-router request counters (a metrics entrypoint the control stack exposes to the API container only — nothing in the request path). The idle clock starts at the later of the last deploy and the API’s own start: a restarted control plane forgets when a stack was last visited, so the cost of a restart is one extra idle period awake, never an early sleep. If the metrics endpoint cannot be read (a control stack from before 0.26.0), idle never triggers — the server logs that once — and after still works.
  • after reads the newest container’s start time from docker. No clock to lose.
  • Never for kind: shared (every preview that depends on it would go with it), never while a job is in flight, never twice.

What sleep runs is docker compose down --remove-orphans — without -v — or docker stack rm under swarm, which never touches volumes. That is the whole difference from tearing down. Waking is up, exactly: axis up hooks are idempotent by contract and re-capture their outputs, so nothing has to be remembered between the two. Readiness watches the wake like any deploy.

By hand, the same two verbs:

Terminal window
curl -s -X POST https://api.preview.example.com/api/deployments/pr-123/sleep -H "Authorization: Bearer $PSTACK_TOKEN"
# → 202 { "job": { "id": "sleep-pr-123-…", "action": "sleep", … } }
curl -s -X POST https://api.preview.example.com/api/deployments/pr-123/wake -H "Authorization: Bearer $PSTACK_TOKEN"
# → 202 { "job": { "action": "wake", … } }

GET /api/deployments/:id carries the policy and the state, separately — sleep is what the spec asks for, asleep is the record written when it happened:

"orchestrator": "swarm",
"sleep": { "idle": "2h", "after": "3d" },
"asleep": { "since": 1787000000000, "reason": "idle 2h",
"hosts": ["app-pr-123.preview.example.com"], "rules": [] }

hosts and rules are what the catch-all router recognises as this deployment’s: they are captured from its live Traefik labels the moment before teardown, so a router you wrote by hand is recognised exactly like a generated one, and a wildcard subdomain (*.app-pr-123.…) still wakes it. A deploy or a teardown clears the record; replacing the spec keeps it. Clearing the record does not hand the hostname back — read the next paragraph before assuming it does.

How a request finds its way back: init renders a catch-all router on the pstack container (priority 1, HostRegexp over the whole *.<domain>). While a preview’s containers run, its own router wins; when they do not, the request lands on the API with the original Host. If that hostname is one this control plane is still holding, every stage below answers 503 with Retry-After: 5 and an x-pstack-wake: 1 header — so a script sees “not yet” rather than a misleading 200 — and the page polls itself, reloading the moment that header stops coming.

What the visitor reads changes with the stage, and there are three:

Stage The page says It ends when
asleep “pr-123 was asleep. It is being brought back now” up returns — the containers now exist
starting “pr-123 is awake and its containers are starting — it has not answered a request yet” readiness settles, either way
failed “Your preview could not start”, quoting the reason (app: exited with code 1) not on its own

The hostname stays this control plane’s for all three, not just the first. The sleep record is cleared the moment up reports success — which is when the containers are created, not when the app answers — and a control plane that let go of the hostname there had nothing left mapping it to a deployment, so the request fell through to “any non-/api/ path is the UI” and the visitor got the pstack dashboard on their preview’s own URL. That is why starting is its own stage and not a longer asleep: it is the true sentence, and it keeps the hostname.

What ends starting is the readiness watch (§6), not a timer of its own — ready hands the hostname back to Traefik, failed or timedout turns the page into the failure row. So the spinner’s bound is readiness’s own deadline (PSTACK_READINESS_TIMEOUT_MS, 180 s), and what replaces it names the failure and then keeps answering: a preview that cannot start must say so on every reload, not fall through to the dashboard on the second one.

Two failures, and they retry differently, because one of them is not really a failure of the wake:

  • The wake job failed — an image that no longer pulls, an axis hook that threw. The stack is still asleep, the page quotes the failing step, and a reload retries it after a minute.
  • The wake job succeeded and the containers died. docker compose up returns when containers are created, so this is an ok job and a crashed app. The page quotes the container’s own reason, and reloading does not try again — there is no sleep record left for a request to act on. POST …/wake, or a deploy, is what tries again.

Two things this page cannot do, and both are worth knowing before you go looking:

  • It cannot replace the 502. Once Traefik has the container’s route, the request reaches the container and never reaches pstack at all. The window this page covers is the one before that.
  • A script cannot tell the stages apart from the headers. All three are 503 + x-pstack-wake: 1; only the body differs. Poll for the header to disappear, which is what the page’s own script does.

Under HTTP-01, Traefik serves the certificate it already issued for the hostname while the stack was live. Under DNS-01 the wildcard covers it. A hostname that was never live has no certificate under HTTP-01 — that is the one case the spinning-up page appears behind a browser warning.

Two events narrate it: stack.slept { stack, deployment, reason, hosts } and stack.woken { stack, deployment, by } — by is request:<hostname> when traffic woke it, or who asked. One thing to know about swarm logs: docker service logs has no --until, so GET …/logs?until= answers 400 on a swarm stack rather than quietly widening the read.

“Can you look at the logs of PR 123?” used to mean creating an account for someone who will sign in once. A share link is a URL that opens that deployment’s details and log view, and nothing else, until it expires:

Terminal window
curl -s -X POST https://api.preview.example.com/api/deployments/pr-123/share \
-H "Authorization: Bearer $PSTACK_TOKEN" -H 'content-type: application/json' \
-d '{ "views": ["details", "logs"], "ttl": "24h" }'
{ "url": "https://control.preview.example.com/deployments/pr-123/public-logs-view?token=eyJ…",
"token": "eyJ…", "views": ["details", "logs"], "expiresAt": 1787086400000 }

views default to both; ttl defaults to 7d and caps at 30d. The same panel is on the deployment’s Danger tab (it mints a credential, so that is where it lives): pick the views and the expiry, copy the link once.

What the token is: an HS256 JWT signed with PSTACK_TOKEN, carrying { dep, views, exp }. It travels as ?token= in the query string — by design, because the log view follows logs over an EventSource, and a browser cannot put a header on one. It also works as a bearer for a script:

Terminal window
curl -s "https://api.preview.example.com/api/deployments/pr-123/logs?tail=200&token=eyJ…"
curl -s https://api.preview.example.com/api/deployments/pr-123 -H "Authorization: Bearer eyJ…"

What a link can reach, enforced before any route: GET /api/deployments/:id (+ /runtime, /readiness) with the details view; GET …/logs and …/logs/stream with the logs view; its own deployment only; stored variables only (a ?PR=8 from a link holder does not resolve another stack). Everything else answers 403. An expired or tampered token answers 401. The raw PSTACK_TOKEN is never accepted from a query string — only a JWT is.

There is no per-link revocation: nothing about a link is stored (a table of issued links would be a row describing a credential), so the TTL is what bounds a leaked one. Rotating PSTACK_TOKEN (PSTACK_TOKEN=<new> pstack init …) invalidates every link at once; pstack upgrade deliberately does not rotate it, so links survive upgrades. The event share.created { deployment, views, expiresAt, by } says a link was minted — never the token.