Skip to content
MSO CloudDocumentation

Deployment Guide

On this page

Scope#

This guide covers local bring-up, environment configuration, and the release checks required before deploying the YNG Unified Commerce Intelligence Platform.

Documentation site (Cloudflare Pages). The public docs site is built with pnpm docs:build-site into docs/.site/ — only cleared .html pages ship, never raw .md sources or internal files. Point the Cloudflare Pages project's Build command at pnpm docs:build-site and its Output directory at docs/.site. See Xuất bản trang tài liệu for the full procedure and why serving raw docs/ exposed CREDENTIALS.md.

Prerequisites#

  • Node.js 26.13.1 (see .nvmrc; Node 26 removed Corepack — install pnpm via npm install -g pnpm@12.23.0)
  • pnpm 12.23.0 (see root packageManager)
  • Docker Desktop or Docker Engine with Compose
  • A .env file derived from .env.example

Local Bring-Up#

pnpm install
cp .env.example .env
./scripts/start-dev.sh

./scripts/start-dev.sh starts Postgres, Redis, and RustFS, runs migrations, seeds sample data, then launches pnpm dev (web + worker) in a detached session and returns control to the caller — logs go to .dev-server.log, stop with ./scripts/stop-dev.sh. Pass --foreground to stream logs in the terminal (blocks; needed for Playwright e2e), or --no-app to bring up the data plane only. Migration generation is opt-in for schema authors with GENERATE_MIGRATIONS_ON_START=1 ./scripts/start-dev.sh.

Default URLs:

  • Web: http://localhost:${WEB_PORT:-3000}
  • Cube: http://localhost:${CUBE_PORT:-4000} when started with --with-cube
  • Postgres: localhost:${PG_PORT:-5432}
  • Redis: localhost:${REDIS_PORT:-6379}
  • RustFS S3 API: localhost:${MINIO_API_PORT:-9000}
  • RustFS Console: localhost:${MINIO_CONSOLE_PORT:-9001}

If those ports are occupied, override the port variables in .env before startup.

Cube Local Ops#

Cube is optional for local boot, but required for the BI/reporting demo.

./scripts/start-dev.sh --with-cube
curl -fsS http://localhost:4000/livez
RUN_CUBE_E2E=1 pnpm cube:verify-tenant-isolation
RUN_CUBE_E2E=1 pnpm cube:verify-metric-parity

The Cube image copies infra/cube/schema at build time. After changing metric catalog or report cube templates, run:

pnpm cube:generate
docker compose --profile cube build cube
docker compose --profile cube up -d cube

Never configure Superset or other BI tools to read app Postgres directly. Use Cube SQL API only, so JWT security context and Postgres RLS remain in the data path.

Local Environment Variables#

  • DATABASE_URL
  • REDIS_URL
  • SESSION_SECRET
  • NEXTAUTH_SECRET
  • NEXTAUTH_URL
  • ENCRYPTION_KEY
  • ENCRYPTION_KEY_VERSION

Optional but commonly used:

  • GEMINI_API_KEY
  • OLLAMA_BASE_URL (external host, self-hosted endpoint, or Ollama Cloud; Compose never runs Ollama)
  • RESEND_API_KEY
  • RESEND_FROM
  • S3_ENDPOINT
  • S3_BUCKET
  • S3_KEY
  • S3_SECRET

Production Deployment#

Production uses the tracked docker-compose.prod.yml.example topology and an operator-owned, untracked .env.prod (+ docker-compose.prod.yml, an exact untracked copy of the template — never commit either file). One script drives every deploy:

cp docker-compose.prod.yml.example docker-compose.prod.yml   # first install only
cp .env.prod.example .env.prod                               # first install only
# Replace every placeholder using the deployment secret manager.
./scripts/start-prod.sh                 # build + migrate + deploy
./scripts/start-prod.sh --with-cube     # also converge the Cube service
./scripts/start-prod.sh --no-build      # reuse existing images (must already exist)

There is no --bootstrap/--upgrade flag to choose — start-prod.sh decides which mode to run by querying the database for an existing super-admin after migrations apply, and always takes the safe path for whichever state it finds. Never run docker compose directly against this stack; the shell profile on this host exports env vars for a different stack that would silently shadow .env.prod (Host rule / DB password mismatch) — use ./scripts/deploy-prod.sh <compose args> for any one-off raw Compose command instead.

Production requires separate migration-owner, yng_app, yng_worker, yng_archive, and yng_cube credentials plus the bootstrap/WebAuthn/session/ encryption/storage values declared in .env.prod.example. CUBE_API_SECRET must be 64 hexadecimal characters when Cube is enabled.

The tracked topology is hardened and CI builds every tracked production service image, but it does not yet boot-smoke, scan, attest, or sign every artifact. That supply-chain gap and the runtime ACL blocker in docs/SECURITY.md prohibit claiming production readiness from a successful wrapper run alone.

Production Topology#

Traefik (on the external balancer network) is the only inbound path. Three router families all point at the same web containers, distinguished only by which host/cert path served the request:

graph TD
  internet((Internet))

  subgraph netBalancer["balancer network — external, shared with Traefik"]
    traefik[Traefik v3]
  end

  webOld[web replica — old]
  webNew[web replica — new, rollout only]

  subgraph netInternal["internal network — internal: true, no route out"]
    pg[(postgres)]
    redis[(redis)]
    rustfs[(rustfs)]
    cube[cube — optional, --with-cube]
  end

  subgraph netEgress["egress network — outbound NAT only"]
    external((connector / AI / email / storage APIs))
  end

  worker[worker + archive-worker]
  pdfbrowser[pdf-browser]

  internet -->|HTTPS| traefik
  traefik -->|"legacy DOMAIN router — Host(DOMAIN), HTTP-01"| webOld
  traefik -->|"tenant wildcard router — TRAEFIK_HOST_RULE, DNS-01 *.msocloud.net"| webOld
  traefik -->|"white-label router — GET /api/edge/traefik-dynamic, per-domain HTTP-01"| webOld
  traefik -.->|routed only once healthy, during a rollout| webNew

  webOld --> pg
  webOld --> redis
  webOld --> rustfs
  webOld --> cube
  worker --> pg
  worker --> redis
  worker --> rustfs

  webOld --> external
  worker --> external
  pdfbrowser --> external
  webOld -.->|PDF export, WebSocket| pdfbrowser

The legacy router matches the exact DOMAIN host and holds an HTTP-01 cert. The tenant wildcard router matches TRAEFIK_HOST_RULE (org subdomains + the msocloud.net apex) and holds a DNS-01 wildcard cert — the only challenge type that can prove a *.msocloud.net SAN. White-label customer domains get their own per-domain HTTP-01 router, added dynamically: Traefik's HTTP provider polls GET /api/edge/traefik-dynamic (bearer TRAEFIK_CONFIG_TOKEN) and renders one router per active verified domain, all pointing at the same shared web target — adding a customer domain needs zero manual Traefik edits. See ADR 0016 and the tenant-domains runbook for the full routing design.

What Runs Where#

Service Image source Network(s) Restarted by a routine deploy?
postgres pulled, pinned digest internal Never — up -d --no-recreate
redis pulled, pinned digest internal Never — up -d --no-recreate
rustfs pulled, pinned digest internal Never — up -d --no-recreate
rustfs-init built, one-shot internal Runs once per deploy (restart: no)
migrate built (infra/migrate/Dockerfile) internal Runs once per deploy (restart: no)
production-init built, one-shot (bootstrap mode only) internal Runs once, bootstrap only (--no-deps skips it on an upgrade)
web built (apps/web/Dockerfile) internal, balancer, egress Rolling — overlapped old/new replicas
worker built (apps/worker/Dockerfile) internal, egress In-place recreate
archive-worker built (extends worker) internal, egress In-place recreate
pdf-browser built (infra/pdf-browser/Dockerfile) internal, egress Candidate overlap, then canonical replacement
cube (--with-cube) built (infra/cube/Dockerfile) internal In-place recreate

Worker recreation delays queued work in Redis. PDF updates use an isolated candidate: web rolls to the matching candidate, the canonical browser updates, then web rolls back to the canonical endpoint. Old and new Playwright protocol versions remain separate during both rolls.

Routine Zero-Downtime Upgrade#

./scripts/start-prod.sh

Why this design: the rolling deploy follows the standard docker-rollout pattern — scale the service up to run old and new side by side, wait for the new one to report healthy, then retire the old one — with Traefik's active load-balancer health check as the gate that decides who receives traffic. web deliberately has no container_name (a fixed name can't run at --scale 2); it publishes a stable Docker DNS alias on internal and balancer instead.

sequenceDiagram
  actor Operator
  participant Script as start-prod.sh
  participant Docker
  participant DB as Postgres
  participant Old as web (old replica)
  participant New as web (new replica)
  participant Traefik

  Operator->>Script: ./scripts/start-prod.sh
  Script->>Docker: build migrate, web, worker, archive-worker, pdf-browser
  Note right of Docker: one image target per invocation — serial builds<br/>avoid a dockerd bake crash (concurrent map iteration)
  Script->>Docker: up -d --no-recreate postgres redis rustfs
  Note right of Script: data plane is never recreated by a routine deploy
  Script->>DB: docker compose run --no-deps --rm migrate
  Note right of Old: old code keeps serving throughout —<br/>migrations are additive-only, safe against the running schema
  Script->>DB: validate super-admin (create-only) — finds an existing one
  Note right of Script: SUPER_ADMIN_COUNT > 0 selects UPGRADE MODE
  Script->>Docker: start isolated PDF candidate and wait healthy
  Script->>Docker: set web PDF endpoint to candidate
  Script->>Docker: up -d --no-build --no-deps --no-recreate --scale web=2 web
  Docker->>New: start the new replica (old kept running, untouched)
  New-->>Docker: Docker healthcheck polls GET /api/health
  Docker-->>Script: new replica reports healthy
  Traefik->>New: starts routing to the new replica
  Note right of Traefik: Traefik only ever routes to a healthy container —<br/>the new replica receives zero traffic until this point
  Script->>Old: docker stop -t 20 (SIGTERM, 20s grace period)
  Traefik->>Old: active LB healthcheck ejects it within ~interval+timeout (≈8s)
  Note right of Traefik: retry middleware (connection-level only, POSTs never<br/>replayed) masks the instant the old listener closes
  Script->>Old: docker rm
  Script->>Docker: up -d --no-recreate --scale web=1 web
  Note right of Script: normalizes Compose bookkeeping; the already-rolled<br/>container is never touched (--no-recreate)
  Script->>Docker: replace canonical pdf-browser and wait healthy
  Script->>Docker: roll web again with canonical PDF endpoint
  Script->>Docker: remove unreferenced PDF candidate
  Script->>Docker: up -d --no-build --no-deps worker archive-worker (+ cube)
  Note right of Docker: worker queues remain in Redis during recreation

If the new replica never reports healthy within PROD_HEALTH_TIMEOUT_SECONDS (default 300s), it is removed and the old replica keeps serving unchanged — see "Failure & Rollback" below.

The production Compose web service must interpolate PDF_BROWSER_WS_ENDPOINT; the script checks this before building or migrating. If a later phase fails, a PDF candidate still referenced by web, or whose references cannot be inspected, remains running. Repair the failed phase and rerun the reviewed deployment before removing that candidate.

Measured floor (2026-07-29, 1-second probe over a full rolling deploy): 166/167 samples 200, one connection reset at the instant the old replica is retired — a keep-alive connection already in flight to it. Requests not yet dispatched are covered by the retry middleware; this single in-flight reset is the practical limit of single-host Compose without app-level connection draining.

First-Time Bootstrap#

On a fresh database (no super-admin row yet), start-prod.sh takes the other branch after the same build/migrate/validate steps: it scrubs any is_sample = true rows, starts pdf-browser and waits for health, then starts web, worker, archive-worker (+ cube) with --no-build --no-deps. There is no existing web replica to overlap. See the go-live runbook for DNS/Traefik one-time setup and org provisioning after the stack is up.

Special Cases#

  • First adoption of the rolling deploy, or any Traefik label edit. If the running web container's traefik.* labels differ from what the current compose config would render, roll_web cannot safely overlap two differently-labelled definitions of the same Traefik service — it falls back to a one-time in-place recreate (brief downtime) instead of an undefined proxy state. This is expected the first time this host runs the rolling path, and again any time the compose template's web labels change.
  • Data-plane config changes (Postgres/Redis/RustFS image, command, or resource limits). A routine deploy never recreates postgres/redis/ rustfs (--no-recreate). Migration, template-update, bootstrap and cleanup one-shots also use --no-deps after the database health check, preventing implicit dependency recreation. If one of those genuinely needs to change, do it in an explicit maintenance window after review: ./scripts/deploy-prod.sh up -d postgres redis rustfs.
  • --no-build skips the build step entirely — the images referenced by the current compose config must already exist locally, or the up phase fails.
  • --with-cube adds the cube profile to every phase of the run (build, health wait, in-place recreate); omitting it on a later deploy leaves any already-running cube container untouched (Compose does not stop a profiled service just because the flag was left off).

Object Store (RustFS)#

  • The in-cluster object store is RustFS 1.0.4, pinned by tag and digest, on the rustfs_data volume; the app reaches it at http://<prefix>-rustfs-prod:9000 (path-style). Root credentials are still MINIO_ROOT_USER/MINIO_ROOT_PASSWORD, mapped to RUSTFS_ACCESS_KEY/ RUSTFS_SECRET_KEY; S3_KEY/S3_SECRET must equal them. The console is disabled (RUSTFS_CONSOLE_ENABLE=false); the healthcheck is /health/ready.
  • RustFS cannot read MinIO's on-disk format. Data moves over S3 only: scripts/ops/migrate-minio-to-rustfs.sh mirrors the bucket and exits 0 only on count, byte, Content-Type and per-object ETag (or content sha256 for multipart) parity. It never writes to MinIO and is safe to re-run.
  • Backups and DR snapshots export the bucket over S3 (mc mirror in the rustfs-init image), never by copying the data directory.
  • The retired minio_data volume stays declared and unmounted until the migration is signed off; rollback restores the previous docker-compose.prod.yml and redeploys web/worker.
  • scripts/ops/storage-s3-smoke.mts exercises @yng/storage (put, head, get, download, presigned GET/PUT, delete) against a live endpoint.

Cutover from MinIO

  1. Deploy the new compose file with the data plane only: docker compose --env-file .env.prod -f docker-compose.prod.yml build rustfs-init, then ... up -d --no-recreate rustfs, then ... run --rm rustfs-init. The old MinIO container keeps serving.
  2. Pre-copy online: scripts/ops/migrate-minio-to-rustfs.sh (expect PARITY: PASS).
  3. Stop writers: docker compose ... stop web worker archive-worker.
  4. Final copy: scripts/ops/migrate-minio-to-rustfs.sh (expect PARITY: PASS).
  5. Switch: ./scripts/start-prod.sh (starts web/worker on the RustFS endpoint).
  6. Stop, do not remove, the old container: docker stop msocloud-minio-prod.
  7. Rollback: restore the previous compose file, docker start msocloud-minio-prod, re-run ./scripts/start-prod.sh; copy objects written after cutover back with mc mirror (no --overwrite, no --remove).

Failure & Rollback#

  • New replica never becomes healthy: it is removed (docker rm -f); the old replica was never touched and keeps serving. A failed deploy degrades to "nothing changed," not an outage.
  • Code rollback: after migration 0259, retain the current source, enforcing migrator image and bootstrap tools. Restore only reviewed previous web/worker image tags and their matching PDF-browser image, then run the current ./scripts/start-prod.sh --no-build. Rehearse those exact images against the enforced database before using them; keep the numeric(18,4) conversions column from migration 0260. An old migrator widens permissions and an old bootstrap reads retired password fields; see ADR 0054.
  • Full stop (not part of a routine deploy): ./scripts/stop-prod.sh removes every container including web replicas but preserves volumes; --volumes additionally wipes Postgres/Redis/RustFS (and retired MinIO) data and requires typing wipe to confirm.

Deploy Guardrails#

  • scripts/verify-prod-compose.mjs renders the untracked live docker-compose.prod.yml and the tracked .example template and asserts they are structurally identical modulo container identities/aliases — including the rolling-deploy shape itself (web has no container_name, publishes DNS aliases on internal+balancer, and declares the Traefik active load-balancer healthcheck + retry middleware labels). Runs before Docker starts anything.
  • Placeholder tripwires: start-prod.sh aborts before touching Docker if .env.prod still contains a documented placeholder/dev-value secret, or if a secret that must be 64 hex characters isn't.
  • Serial image builds: one docker compose build <target> per image, never a combined multi-target build — Compose v5's buildx bake solver races the daemon (Go concurrent-map-iteration crash) when building several targets in one job graph.
  • scripts/deploy-prod.sh is the only sanctioned raw-Compose entry point: it unsets every key .env.prod defines from the shell environment before invoking docker compose, so a stale shell export from a different stack on this host can never shadow .env.prod silently.

Release Checklist#

One command from the repo root is the canonical complete local gate:

pnpm run verify

audit:all in package.json is the ONE place the static audit scripts are enumerated — never re-list them by hand in a doc, hook, or workflow. verify:data reconciles metric surfaces against live data, so it needs the local data plane up and seeded; CI runs it against a freshly migrated + seeded database. The pre-push hook intentionally runs a fast non-DB subset; CI adds isolated production build/topology, fresh-database data/RLS gates, and Playwright smoke.

For operator journeys and artifact evidence:

pnpm run test:e2e              # assumes the app is already running on :3000, seeded

For the documented local smoke path:

./scripts/start-dev.sh
pnpm run test:e2e

The full pre-release checklist (DB, config, docs, operability, rollback) lives in docs/RELEASE-CHECKLIST.md.

Feature Done Checklist#

Use this as the minimum ship gate for any feature branch, not just releases.

  • Requirements confirmed: user impact, org scope, failure mode, and rollback path are clear.
  • Package boundaries respected: shared logic moved to packages/*, not duplicated in apps/web.
  • DB changes are complete: migration, indexes, RLS policy, is_sample, and seed/backfill impact reviewed.
  • Security changes are complete: auth scope, rate limit, audit trail, and secret handling reviewed.
  • Async flows are complete: idempotency, retry policy, dead-letter behavior, and worker observability reviewed.
  • UI changes are complete: Vietnamese copy, empty/loading/error states, desktop + mobile verified.

Verification Matrix#

Run the relevant checks for the surface you changed:

  • All changes:
    • pnpm run verify
  • UI or routing changes:
    • Use the project browser-verification router for the touched journey.
    • Add/run the smallest matching Playwright spec only when operator-critical behavior needs a deterministic regression gate. Full pnpm run test:e2e is release/CI scope, not the default local smoke.
    • Verify the touched desktop/mobile state and relevant Vietnamese copy; do not claim an unrun full suite.
  • Schema or RLS changes:
    • pnpm db:migrate
    • pnpm tsx scripts/generate-sample-data.ts
    • Explicit tenant-isolation verification with at least two org contexts
  • Worker, connector, or webhook changes:
    • Start local infra and worker
    • Verify retry, duplicate delivery, and failure handling paths
    • Verify logs/metrics expose connector, org, duration, and row counts
  • Metric or rollup changes:
    • pnpm run verify:data — new metric surface gets a new reconciliation assertion in scripts/audit/data-reconciliation.ts
  • AI changes:
    • Verify runtime AI config resolves from ai_connections via resolveOrgAi (@yng/ai/server) → createFailoverLanguageModel — ordered per-org candidates with provider/model failover (ADR 0005, docs/adr/0005-ai-multi-connection-failover.md). ai_configs is only a single-row back-compat pointer synced to the primary connection; no call site reads + decrypts it inline.
    • Verify the provider/model is never shown to end users (admin/settings AI screens excepted).
    • Verify secrets never leave server responses or logs.
    • Verify timeout, fallback, and budget behavior.

Review Evidence#

Before requesting review, attach or summarize:

  • Commands run and whether they passed
  • Screenshots or short recordings for UI changes
  • API/request examples for contract changes
  • Migration notes and rollback notes for schema changes
  • Known follow-ups that are explicitly non-blocking

Deployment Notes#

  • Org-scoped data must continue to flow through orgProcedure; do not bypass RLS in deployment patches.
  • Connector credentials stay envelope-encrypted; production secrets must come from environment and per-org config, never checked into the repo.
  • NEXTAUTH_URL must match the public origin exactly, including port in non-production environments.
  • When changing ports locally, update WEB_PORT, PG_PORT, REDIS_PORT, and MinIO variables together so the startup script and Docker compose file stay aligned.

In this section