Deploying to production

Ship a Redelay Go backend to Docker Swarm — a Mode B image built with SSH-forwarded private modules, a swarm stack that survives node reboots, CI on every push, version-tag releases from main, one-click rollback, and the rules we learned the hard way.

17 min readGuide

This is how the Redelay reference backend (api.redelay.com) and the gymmer.com backend ship. The app repository owns three files, and nothing outside it is needed to build or deploy:

FileJob
DockerfileBuilds every binary from this checkout alone, fetching private framework modules over SSH
docker-swarm-stack.ymlThe swarm services: placement, healthchecks, rollout and rollback policy, Traefik labels
.github/workflows/ci.ymlBuild, vet, gofmt and the full test suite (on throwaway infrastructure) — every push to main, every PR, and the first job of every release
.github/workflows/deploy-production.ymlA version tag on main → CI → build → docker stack deploy → wait for the rollout; a manual run with an older tag is the rollback

It relies on the app being Mode B: go.mod pins released framework tags with no replace (see Creating a Go App → Mode B). A build that relies on sibling checkouts breaks as soon as the siblings' branches drift apart. The Redelay backend's own CI failed for seven weeks for exactly this reason before it moved to Mode B.

Picking up framework changes

A deployed app gets framework changes only when you move a pin:

shell
# in the library: tag the change
git tag v0.44.0 && git push origin v0.44.0
# in the app: move the pin, build, commit
go get github.com/redelay/go-modules@v0.44.0
go mod tidy && go build ./... && go test ./...

Tagging a library never changes another project's build, because every app keeps its own pins. When several apps share the framework, starting a new app on the same pin set as one already in production gives you a known-good baseline.

The Dockerfile

dockerfile
FROM golang:1.25 AS build
WORKDIR /src

ENV GOPRIVATE=github.com/redelay/*,github.com/flowdsl/*,github.com/FlowDSL/*,github.com/dreplyai/* \
    GOTOOLCHAIN=local CGO_ENABLED=0 GOOS=linux

COPY go.mod go.sum ./
RUN --mount=type=ssh \
    mkdir -p -m 0700 ~/.ssh && \
    ssh-keyscan -t rsa,ecdsa,ed25519 github.com >> ~/.ssh/known_hosts 2>/dev/null && \
    git config --global url."git@github.com:redelay/".insteadOf "https://github.com/redelay/" && \
    git config --global url."git@github.com:flowdsl/".insteadOf "https://github.com/flowdsl/" && \
    git config --global url."git@github.com:dreplyai/".insteadOf "https://github.com/dreplyai/" && \
    for i in 1 2 3; do go mod download && exit 0; sleep $((i * 15)); done; exit 1

COPY . .
RUN GOWORK=off go build -trimpath -ldflags="-s -w" -o /out/api ./cmd/api
# … one `go build` per binary, then a slim runtime stage that copies /out/*

# In the runtime stage: the build this image is (go-framework ≥ v0.20.0
# reports it on /health/live and to the admin's version footer).
ARG VERSION=dev
ARG COMMIT=
ENV APP_VERSION=$VERSION APP_COMMIT=$COMMIT

Key points:

  • --mount=type=ssh forwards the deploy key for that single RUN, so the key never lands in an image layer. A key added with COPY stays recoverable from the layer even in a stage you throw away.
  • Use one insteadOf rule per private org. A single rule for all of https://github.com/ would also send public dependencies over SSH.
  • Write the module path's case, not the repo's. The module path github.com/dreplyai/… is lowercase even though the repo is DreplyAI/…. insteadOf matches the URL string exactly, so a rule written with the repo's casing never fires.
  • Pin known_hosts with ssh-keyscan. Don't use StrictHostKeyChecking=no: with checking off, the build would hand its key to whatever answered on port 22.
  • Retry go mod download. It makes hundreds of fetches, and one hiccup shouldn't fail an otherwise good build.
  • .dockerignore must exclude .env*, go.work and go.work.sum.

Build it locally with a key file, the same way CI does:

shell
docker buildx build --ssh default=$HOME/.ssh/id_ed25519 -t myapp-api .

The swarm stack

Three settings decide whether the service recovers on its own:

yaml
x-deploy-policy: &deploy-policy
  restart_policy:
    condition: any        # not on-failure, and no max_attempts
    delay: 5s
  update_config:
    parallelism: 1
    order: start-first
    failure_action: rollback
    monitor: 120s         # how long a new task must stay healthy
  rollback_config:
    order: start-first
    failure_action: pause
Don't use on-failure with max_attempts. If a node reboots and reaches the registry over Tailscale, image pulls fail until Tailscale is up. A capped policy uses up its attempts in that window and leaves the service at 0 replicas with no retry. Swarm won't reschedule it. redelay.com and flowdsl.com were down for about 45 hours this way in September 2026.
  • monitor is what makes failure_action: rollback work. Without it, a task that crashes after its first healthcheck still counts as a successful update.
  • Give every service a real healthcheck. Distroless images have no wget or curl, so ship a small static /healthcheck binary that requests $HEALTH_URL.
  • Keep the stack name stable. docker stack deploy under a new name starts a second stack, and both then claim the same Traefik hosts.

Releases: tag on main, roll back by tag

main is the release line. A release is an annotated tag on a commit that is on main, and the tag push deploys it:

shell
git tag -a v2026.10.16-2 -m "what changed" origin/main
git push origin v2026.10.16-2

Apps use vYYYY.MM.DD-N; libraries use semver (vX.Y.Z). The deploy workflow runs four jobs:

JobWhat it does
resolveWorks out the mode and version. A tag must match the format and its commit must be on origin/main. If a newer version tag already exists on main, the run is marked superseded: CI still runs, deploy is skipped, so an older tag that finishes late never rolls production back
ciCalls ci.yml (uses: ./.github/workflows/ci.yml) on the tag's commit — nothing builds or deploys unless it passes
build-and-pushBuilds once and tags the image with the version and a timestamp-sha; pushes to the registry
deploydocker stack deploy with the stack file of that version, waits for the rollout, health-checks the public URL, cleans the registry (keeps the last 10 images, protecting every digest a service uses)

Rollback is a manual run with an earlier tag. It skips CI and the build, redeploys that version's existing image with that version's own stack file, and takes about 3 minutes:

shell
gh workflow run "Deploy API to Production" -R <org>/<app> -f tag=v2026.10.16-1

concurrency: {group: deploy-production, cancel-in-progress: false} keeps one deploy at a time and never cancels one half-way: a cancelled stack deploy can leave services on mixed versions. Each service's image tag is the version, so docker service ls shows what is live.

CI

ci.yml runs on every push to main, on pull requests, and as the first job of every release. Tests that need a database skip themselves when none is reachable (testutil.TestDB). So CI starts a throwaway MongoDB from the registry mirror on a free port, sets TEST_MONGO_URI, and fails if any test still skipped for lack of it. A green run has to mean the tests ran. The first run on the Redelay backend found five never-formatted files, a gap nobody had noticed.

Build and deploy steps

The build and deploy jobs run on a self-hosted runner on the swarm manager:

  1. Guard. Fail if the checkout contains a go.work, a .env, or any replace in go.mod.
  2. Find the deploy key. Probe the candidate keys with git ls-remote against one repo per private org, and use the first key that can read all of them. A repository or org variable (GO_MODULES_SSH_KEY) can override the choice.
  3. Build and push with docker/setup-buildx-action using driver-opts: network=host, passing --build-arg VERSION=<tag> --build-arg COMMIT=$GITHUB_SHA (the Nuxt admin image takes the same VERSION as NUXT_PUBLIC_APP_VERSION).
  4. Deploy. Run docker stack deploy with secrets sourced from an env file on the manager (never from the repo).
  5. Wait for the rollout. Poll each service's UpdateStatus.State. Fail on rollback_* or paused, and print the task errors and recent logs.
  6. Run a health check against the public URL, then clean up the registry.
network=host is required when the registry is on a Tailscale address. With the default docker-container driver, BuildKit runs on the Docker bridge, and the bridge can't route to 100.x addresses. The build succeeds and then the push fails after minutes of retries with dial tcp 100.x.x.x:5000: i/o timeout, which looks like a registry outage.

Two GitHub quirks:

  • Pass --ssh default=<key path>, not plain default. A runner installed as a service has no $SSH_AUTH_SOCK.
  • The workflow file must exist on the default branch. Otherwise GitHub never registers it: tag pushes start nothing and workflow_dispatch returns 404.

The Redelay backend's ci.yml and deploy-production.yml are the reference copies.

For a Nuxt admin, redelay/admin is the reference: the same jobs, with the image build as CI, a build context assembled from the app and the base layer at its newest release tag (scripts/assemble-context.sh), the tag baked in as NUXT_PUBLIC_APP_VERSION, and a final check that the live page serves that tag.

Waits before the rollout

A rollout restarts every task, and a restart kills whatever that task was doing. Apps with long-running work put automatic waits in the deploy job, between the build and docker stack deploy, instead of relying on someone remembering to check:

  • Running schedules. Poll a gauge of running scheduled jobs (Nameniac: max(nameniac_schedules_running) in Prometheus) until it reads 0, with a deadline (25 min), then deploy anyway: the scheduler retries interrupted runs. If the gauge is missing, say so and deploy; don't block forever on an unknown.
  • Time windows the app must not be restarted in (Nameniac: domain-catch windows read from the stack file, plus any live race). Same shape: poll, deadline, deploy.

Each wait gets a skip_* boolean input on workflow_dispatch, for a hotfix that can't wait. On a tag push the inputs are empty, so every wait runs.

Rollback and migrations

A rollback runs no CI, no build and no migrations: the older build starts on the schema the newer build left behind. That is only safe if every migration is expand/contract: it adds before it removes, and the build already deployed keeps working on the migrated schema. Apps with migrations enforce it in the release path:

  1. Run the new build's migrations as one-shot jobs while the old build is still serving. The job runs the same image with MIGRATE_ONLY=1, which app.MigrateIfAsked() (main's first line, go-framework v0.34.2+) turns into app.Migrate(): migrations, then exit 0 or 1, and nothing else starts. Set MIGRATIONS_TIMEOUT on the job only (default 5m; e.g. 30m, or 0 for no deadline) when a migration is long, such as a home-region backfill of millions of rows. The job holds the app's migrations lock and keeps renewing it, so a replica that boots meanwhile waits instead of running the same scripts. Run one job per deploy that runs every binary in turn, not one job per binary (repeated service create/remove cycles have destabilised a manager's dockerd). Remove the job right after you read its result, and keep it idempotent. A completed Swarm replicated-job keeps re-running until it is removed, even with --restart-condition none. On 2026-10-18 one ran 157 times in 3 minutes (leader on Docker 27.3.1, task on 29.9.1). So: create → wait for exit → read the exit code and logs → docker service rm in the same step, and treat every migration as safe to run twice. A plain replicated service with restart_policy: on-failure (aiplatform's seed) is not affected: it runs once per deploy.
  2. Check the old build against the migrated schema (health plus a few real reads). If it fails, stop before anything rolls out and alert.
  3. Then roll out.

Step 2 is what makes a later rollback safe, so the release path runs it and the rollback path skips it.

A frontend with an e2e gate

A Nuxt app deploys the same way: a version tag on its main, the image tagged with the version, a rollback by running the workflow with an older tag. Two differences:

  • The gate is e2e against a candidate, not unit tests. The new image runs as a candidate stack beside production, reachable only with a secret header. The whole Playwright suite runs against it, and production is deployed only if it passes. A rollback skips the gate: that image passed it when it was released.
  • When the build lives in another repo (a monorepo builds the app from a submodule), that repo's workflow takes the tag as a workflow_dispatch input. It checks the tag is on the app's main and checks the submodule out at the tag. A tag already in the registry means rollback; a new tag must be the newest on main. The submodule's gitlink no longer decides what deploys.

Moving an existing app from a deploy branch to tags

  1. Change the workflow on main: tag trigger, resolve job, image tagged with the version, stack file checked out at the tag. Keep the app's own gates (the waits above, migration checks, probes, smoke tests); only the trigger and the versioning change.
  2. Make the health check prove the version: /health/live must answer "version":"<tag>".
  3. Push the first tag and verify it by behaviour (see the rules below).
  4. Retire the deploy branch: delete it, or leave it with no trigger, and update the app's README/DEPLOY notes.
  5. Rollback needs two tag releases. Images built before the switch carry timestamp tags, not versions, so the first tag has nothing older to roll back to. Until the second tag ships, roll back by redeploying the old timestamp image by hand.

Deployment rules

What we learned running these deploys, each from a real incident:

RuleWhy
Verify a deploy by behaviour, not by the workflow's green tick. Check that the services run the new image tag, that the health URL answers, one functional probe of what changed, and zero error lines in the logs since the rollA push to the wrong branch deploys nothing and still looks done; a swarm auto-rollback reads "N/N replicas"
Prove the new build is serving: curl …/health/live returns the tag (go-framework ≥ v0.20.0); the admin sidebar footer shows every service's versionA green deploy with the old image still answering looks identical otherwise
Healthchecks and balancer probes use /health/live (go-framework ≥ v0.17.2), not the deep /healthThe deep check fails during a Mongo election; a balancer probing it pulls every task out at once
Zero-downtime: update_config.order: start-first + SHUTDOWN_PREDRAIN_SECONDS (~30 s, go-framework ≥ v0.21.0) + SHUTDOWN_DRAIN_SECONDS (≥ v0.15.4) on services behind the proxy; RUNNER_STOP_TIMEOUT_SECONDS and stop_grace_period above their sumRequests in flight survive the roll. Without the pre-drain the old task left Traefik's pool before the new one joined it: 3–7 s of 503s on most deploys
restart_policy: condition: any, no max_attemptsA capped policy left every service at 0 replicas after a node reboot
Never ${VAR:?message} in a stack file; use ${VAR} and fail in the callerdocker stack deploy turns the :? message into the value
Before deploying shared infra, compare the live config hashes with the git tipAnother session may have deployed a change that isn't committed yet; deploying would revert it
Editing a path-triggered deploy workflow: commit with [skip ci] when the change shouldn't deployThe workflow file is in its own paths, so editing it deploys
Check scheduled runs before deploying a worker — better, make the deploy wait for them automatically (see Waits before the rollout)A deploy kills running scheduled jobs; re-run them via next_run_at
Migrations are expand/contract, checked against the build being replacedA rollback runs no migrations: the older build has to work on the newer schema
After any auth or credential change, prove the once-a-day jobs still work (backups first)Mongo auth passed a 24 h gate, then the nightly backup failed for a day: time-series buckets need their own privilege
Libraries: CI on release/<ver> before tagging; never tag on an approval relayed by another sessionA local broker passed what CI's cold broker failed (go-events v0.6.4); a tag can't be taken back
Apps stay on the latest tag of every Redelay library — one PR bumps them allOld pins carry fixed bugs (a v0.4.3 startup stall, an open admin API)
Kafka: the idempotent producer stays off (go-events ≥ v0.6.10 default) unless one goroutine publishessarama fails unrelated concurrent publishes after one failure
Probe concurrently, not sequentially, when checking a fix under load60 sequential 200s hid 60–75 % concurrent 500s
One APP_NAME per app; SERVICE_NAME per service (go-framework ≥ v0.23.0)APP_NAME keys the migrations lock and the scheduler's leader lock: an admin-api on its own name meant a second migrations runner and a second scheduler leader — every schedule firing twice
New stop settings (pre-drain, drain, grace period) take effect from the deploy AFTER the one that ships themOld tasks stop with their old environment: the first roll with SHUTDOWN_PREDRAIN_SECONDS still showed 4 × 502 + 32 timeouts; the next showed none
Measure a roll with a concurrent probe on a real endpoint, not only health endpointsA draining task answers /health and /health/live with 503 by design while still serving every other request, so a health-only probe counts those 503s as failures
Announce every shared-infra change (Traefik/web stack, monitoring, shared stacks, routed-service labels) to the app owners with a UTC window and its scope, and say when it is doneApp deploy gates only see their own repos; a hand-run deploy.sh or a label update leaves no workflow run anyone can see (see Shared infrastructure changes)
Run traefik-label-guard before any Traefik label change (--stack NAME for a stack file, --live after)Mixed traefik.docker.*/traefik.swarm.*, lbswarm on dnsrr, lbswarm + Traefik healthcheck, lbswarm on a failover child, and a missing middleware each took a site down (2026-10-25/26)
Live label edits use --no-resolve-image, then compare task IDsWithout it a moved tag restarts the tasks; even a label-only update can roll a task when the CLI rewrites mounts

Shared infrastructure changes

Shared infrastructure is everything several apps depend on at once:

  • the Traefik web stack;
  • monitoring;
  • the shared data stacks (Mongo, Kafka, Redis, ClickHouse);
  • DNS and the origin watchdog;
  • the swarm topology;
  • Traefik labels on routed services (middlewares, lbswarm).

A mistake there takes down several apps, and no app's deploy gate can see it. App gates list their own organisation's workflow runs. A hand-run monitoring/deploy.sh, a web stack deploy or a docker service update --label-add creates no run, and runners are per GitHub organisation. Coordination is therefore manual, in both directions.

Before:

  1. Announce a UTC window to the app owners (the sessions working on Gymmer, Nameniac, aiplatform and so on). Give its scope: which services change, and whether anything restarts, for example "Traefik rolls one node at a time, ~12 s of errors per node", or "label-only, no restart". Ask whether a deploy of theirs is in flight, and wait for it to finish.
  2. Ship only your diff. Compare the live config names or hashes with main. A config that another session deployed by hand but never committed would be reverted, and a merged but undeployed change would ship alongside yours.
  3. Run the guard: python3 tools/traefik-label-guard.py <stack.yml> --stack <name> from stufio-com/infra. It runs automatically in tools/deploy.sh and in the web stack's deploy.sh.

During:

  • change one service at a time;
  • canary first where you can (whoami.nameniac.com is the shared canary host);
  • for live label edits, use docker service update --detach --no-resolve-image …, then check that the running task IDs are unchanged.

After:

  • verify by behaviour: the public URL through Cloudflare, plus the specific failure you guarded against;
  • check that the origin watchdog drained nothing, the probes are green and no alerts fire;
  • traefik-label-guard --live reports 0 violations;
  • announce that you are done.

Origin lock (cf-only@swarm)

Cloudflare-proxied hosts accept only Cloudflare and our own nodes through the shared ipAllowList cf-only@swarm:

  • Cloudflare IPv4 and IPv6 ranges;
  • the 5 node public IPs, for the origin watchdogs on waw and hel, blackbox and hairpin calls;
  • private and tailnet ranges.

It is defined as labels on web_whoami (aiplatform deploy/web/web-stack.yml), so changing it needs no Traefik restart. Without it, anyone who knows a node IP bypasses Cloudflare's WAF, bot protection and DDoS shielding. A forged Cf-Connecting-Ip is accepted as well, so a rate limit may key on that header only for locked hosts.

  • Opt a router in: traefik.http.routers.<r>.middlewares=cf-only@swarm (put it first in an existing chain). Verify that a direct request from a non-node IP gets 403 and that the same URL through Cloudflare gets 200.
  • Never lock a host Cloudflare does not proxy:
    • the landing-http/landing-https entrypoints, whose customer domains point straight at us;
    • DNS-only hosts such as *.demo.dreply.com, media.stufio.com and hooks.nameniac.com (Stripe).
  • A missing definition fails closed. Traefik drops every router that references it, and those hosts answer 404 (measured). The guard refuses a deploy that would remove it (STILL-REFERENCED), and the alert origin_lock_canary_failing pages when the canary stops answering.
  • When Cloudflare changes its ranges (cloudflare.com/ips), update the label in the web stack file and apply it live.

Monitoring

Probe the public URL with the Prometheus blackbox exporter. That covers every failure a user would see: 0 replicas, a missing Traefik router, TLS, DNS, or app 5xx errors.

yaml
- job_name: public-sites
  metrics_path: /probe
  params: {module: [http_2xx]}
  static_configs:
    - targets: ['https://api.example.com/api/v1/health']
      labels: {project: myapp, service: api}
  relabel_configs:
    - {source_labels: [__address__], target_label: __param_target}
    - {source_labels: [__param_target], target_label: instance}
    - {target_label: __address__, replacement: blackbox-exporter:9115}
yaml
- alert: public_site_down
  expr: probe_success{job="public-sites"} == 0
  for: 3m
  labels: {severity: critical}
Was this page helpful?