Deployment
Blazor Blueprint ships as Docker images run by Docker Compose. There are two shapes, chosen entirely by configuration — same code, same images:
| Full (default) | Lite | |
|---|---|---|
| Containers | Web, InternalApi, BackgroundWorker, Redis, database, plus a one-shot DbMigrator | Web and database — nothing else |
| Compose file | .azure/devops/docker-compose.yml or .github/workflows/docker-compose.yml (plus .postgres / .sqlserver variants) |
docker-compose.lite.yml at the repo root (plus .postgres / .sqlserver variants) |
| Optional Grafana | GRAFANA_ENABLED=true in the pipeline |
COMPOSE_PROFILES=observability |
| Background work | Redis streams, run by the BackgroundWorker | Inside the web process |
| Data Protection key ring | In the platform database, wrapped by the KEK on the bb_kek volume (mounted at /kek in all three app containers) |
In the platform database, wrapped by the KEK on the bb_lite_kek volume (mounted at /kek) |
| Instances | Can scale out (see Scaling out) | Single instance only |
| Deployed by | The shipped CI/CD pipelines, or by hand | By hand — no pipeline builds or deploys Lite |
Start with Lite if one container is enough; move to Full to isolate background work from request serving or to run more than one app instance. For what each service does, see Architecture.
The Full stack
What gets deployed
| Service | Image | Port | Notes |
|---|---|---|---|
blazorblueprint-web |
WEB_IMAGE |
8080, published | The Blazor Server app. The only port published to the network. |
blazorblueprint-internalapi |
APP_IMAGE |
8081, internal | The internal API. A public or partner API belongs in the Web app. See API. |
blazorblueprint-background-worker |
WORKER_IMAGE |
8082, internal | Job-stream consumers and recurring sweeps. |
blazorblueprint-dbmigrator |
MIGRATOR_IMAGE |
— | One-shot schema/index runner. On MongoDB it reconciles indexes (creating missing indexes and replacing ones whose options changed; it drops orphans only with --drop-orphan-indexes); on PostgreSQL and SQL Server it migrates the platform database and every tenant. Exits non-zero on any failure. |
blazorblueprint-mongodb / -postgres / -sqlserver |
mongo:7.0.45 / postgres:16.15 / mcr.microsoft.com/mssql/server:2022-CU27-GDR1-ubuntu-22.04 |
internal | Authenticated, never published. |
blazorblueprint-redis |
redis:7.4.11-alpine |
internal | Cache, SignalR backplane and job streams. Runs with --appendonly yes --maxmemory 2gb --maxmemory-policy noeviction --requirepass …. |
blazorblueprint-grafana |
grafana/otel-lgtm:0.36.0 |
3000, this host only | Optional, off unless GRAFANA_ENABLED=true. See Optional Grafana dashboards. |
The app services wait for a healthy database and a successful DbMigrator (service_completed_successfully), so a failed migration stops the deploy before any app container starts (see Relational Schema Management). With WEB_IMAGE and the others unset, compose uses local blazorblueprint-*:latest images.
noeviction is required — eviction would drop queued jobs. A full Redis refuses writes, stopping every job publish, so size maxmemory for your worst worker outage.
The app containers run non-root with a read-only root filesystem, a 256 MB noexec tmpfs at /tmp, all capabilities dropped and no-new-privileges. Give a feature that writes to disk a named volume rather than removing read_only.
The volumes have fixed names — redis_data, bb_kek (the key-encrypting key) and mongodb_data, postgres_data or sqlserver_data — so the stack finds its data from any directory. Do not rename them: an empty bb_kek over a database with keys stops the app until you supply the recovery key.
Image versions are pinned
Every third-party image is pinned to an exact version and digest (mongo:7.0.45@sha256:…) in the compose files, the pipelines’ test containers and the Dockerfiles, so a deploy never silently picks up a new database version whose upgrade scripts run against your data. A test fails the build on a floating tag, a missing digest, or two files pinning one image differently.
Bumping a pin. .github/dependabot.yml opens weekly pull requests for images and NuGet packages (image major versions are left to you; it does not update the pipelines’ test containers or AspireStack.GrafanaTag). By hand — or for SQL Server’s 2022-CU… tags — resolve the new digest and change every file that uses the image in one commit:
docker buildx imagetools inspect postgres:16.16 --format '{{json .Manifest.Digest}}'Read the release notes first: a datastore upgrade runs against your data on the next deploy.
Datastore credentials
Docker Compose reads these from the shell environment (or your pipeline’s variables). Every compose command — build included — refuses to run without them.
| Variable | Kind | Notes |
|---|---|---|
DATABASE_TYPE |
variable | Optional. mongodb (default), postgresql or sqlserver. Chooses the compose file the pipeline deploys; set it before the first deploy. See Pick your database backend. |
DATABASE_USERNAME |
variable | Required on MongoDB and PostgreSQL, no default. Leave it unset on SQL Server (the account is always sa; the validator rejects anything else). |
DATABASE_PASSWORD |
secret | The database password, whichever backend. |
REDIS_PASSWORD |
secret | Required on every backend. |
MSSQL_PID |
variable | SQL Server only, and required there: Express, Standard, Enterprise, EnterpriseCore, Web, or a 25-character product key. Developer and Evaluation are refused (not licensed for production). You must hold a licence for the edition you name; Express is free but limited. See THIRD-PARTY-NOTICES.md. |
There is one credential pair whatever the backend; the compose files map it onto each image’s own variables.
Generate the passwords like this:
export DATABASE_USERNAME=blazorblueprintexport DATABASE_PASSWORD=$(openssl rand -base64 32 | tr -d '+/=')export REDIS_PASSWORD=$(openssl rand -base64 32 | tr -d '+/=')The tr -d '+/=' is required
Each password goes into a connection string unescaped, and plain base64 contains a / (reserved in the mongodb:// URI) about half the time. The validator also refuses ; and quotes for PostgreSQL and SQL Server, and ,, quotes, \, ;, &, |, <, >, $ and backticks in the Redis password. The database bakes its credentials into the data volume on first start, so a bad password can only be fixed by wiping that volume.
Pick the credentials once, and keep them
- The username and password are fixed at first start. MongoDB and PostgreSQL create the account only on an empty data directory; changing either variable later leaves the database unhealthy and nothing starts. Store both durably.
- Redis must be authenticated. Anyone who can reach an open Redis can forge background work or wipe the queue, and it holds some decrypted cached values (see Security → What the KEK protects against).
- Adding authentication to an existing unauthenticated MongoDB volume is a migration. Create the account inside the running container first, then redeploy.
To use an external database or Redis, edit the Database__ConnectionString or ConnectionStrings__redisCache line in your copy of the compose file for every service that carries it (they outrank deploy.env), then remove the unused service and the depends_on entries naming it.
scripts/validate-deploy-config.sh checks these before a deploy, reporting every problem at once without printing values: presence, the delimiter rules, whitespace, a 12-character password minimum, placeholder-like values, SQL Server’s 3-of-4 character-class rule, and the two database names below. Both pipelines run it; to run it yourself:
DATABASE_TYPE=mongodb bash scripts/validate-deploy-config.shDATABASE_TYPE accepts mongodb (default when unset), postgresql (or postgres) and sqlserver (or mssql).
Application secrets
These reach the three app containers through a git-ignored deploy.env (read with env_file), written by scripts/render-deploy-env.sh — to .azure/devops/deploy.env by default; the GitHub workflow passes .github/workflows/deploy.env. The script escapes values, omits empty optional ones and never prints them. The file is mode 600 on Linux; on a Windows agent the script restricts it with icacls and warns if it cannot — restrict the agent’s work folder to the agent account and administrators either way.
# Required — the script exits with an error if any is emptyWEBAPP_CLIENT_SECRET # Web ⇄ InternalApi client credential (written to both sides)JWT_SECRET_KEY # signs the internal service JWTMESSAGING_SIGNING_KEY # HMAC on every job envelope — identical on every hostDOMAIN_VERIFICATION_SECRET # HMAC for custom-domain TXT verification tokens; use 32+ characters (only presence and the placeholder are checked)Generate them with openssl rand -base64 48 and keep them in your pipeline’s secret store, never in source control. The script refuses the appsettings.json placeholders for MESSAGING_SIGNING_KEY (dev-only-change-me…) and DOMAIN_VERIFICATION_SECRET (REPLACE_BEFORE_PRODUCTION…), and the app refuses to start on them outside Development.
Save the recovery key at initial setup
The key-encrypting key (KEK) that unwraps the encryption keys in the database is generated on the bb_kek volume on first start, and initial setup shows it once as the recovery key. Save it in your password manager. If the volume is lost, set the optional DATA_PROTECTION_KEK secret to it and redeploy — and keep it set from then on. Lose both and every encrypted field and file is gone. See Security → Encryption keys.
The platform address is set in the app
The hostname the application answers on (app.example.com) is entered at initial setup and changed at Platform → Platform Settings; it lives in the platform database, not configuration. Until one is saved, /health reports Degraded while subdomain organisations or custom domains are on (both default on). Organisation subdomains need it to be a domain — not localhost, an IP or a single-label name — plus wildcard DNS and a wildcard certificate for *.{platform address}; otherwise they stay off. There is no cookie-domain setting.
If that address stops resolving (DNS down, domain lapsed), sign in on the server itself at http://localhost:8080: once a platform address is saved, localhost reaches the platform organisation from any connection, with a password (passkeys and Google, Microsoft or Facebook sign-in stay tied to the address). Change the address there if you are moving. See Architecture → Tenant resolution.
Everything else is optional. An unset value is left out of deploy.env, so the app uses appsettings.json:
| Variable | Kind | Takes effect |
|---|---|---|
FACEBOOK_APP_ID / _SECRET, GOOGLE_CLIENT_ID / _SECRET, MICROSOFT_CLIENT_ID / _SECRET |
variable / secret | Every startup, as the fallback for the platform’s sign-in apps. Credentials saved at /Platform/ExternalSignIn (seeded from these at setup) override them. |
REDIS_KEY_PREFIX |
variable | Every startup — set once at first deploy, never changed (see Backups). |
DATA_PROTECTION_KEK |
secret | Every startup. The KEK held outside the bb_kek volume (the recovery key, or one you generated for hosts that don’t share a disk): bbkek1- plus 43 base64url characters. Blank means the file on the volume. |
DATA_PROTECTION_KEY_VAULT_KEY_ID |
variable | Every startup. Keeps the KEK in Azure Key Vault: https://<vault>.vault.azure.net/keys/<name>, without a version; not with DATA_PROTECTION_KEK. See Security → Keeping the KEK in Azure Key Vault. |
DATA_PROTECTION_KEY_VAULT_TENANT_ID / _CLIENT_ID / _CLIENT_SECRET |
variable / variable / secret | The Key Vault service principal — all three or none (none uses a managed identity). Renew the secret before it expires. |
DATA_PROTECTION_KEY_VAULT_MANAGED_IDENTITY_CLIENT_ID |
variable | A user-assigned managed identity; blank uses the system-assigned one. Not with a service principal. |
OTEL_EXPORTER_OTLP_HEADERS |
secret | Every startup. Headers for OTEL_EXPORTER_OTLP_ENDPOINT, usually a vendor API key (Authorization=Basic …). See Observability. |
QUESTPDF_LICENSE_TYPE |
variable | Every startup. Community (default), Professional or Enterprise — see QuestPDF’s Community threshold in THIRD-PARTY-NOTICES.md. An unrecognised value stops the app. |
EMAIL_ENABLED, EMAIL_PROVIDER, EMAIL_API_KEY, EMAIL_SENDER |
variable / secret | Once, at initial setup. Afterwards, /Platform/Email. |
OPENAI_ENABLED, OPENAI_API_KEY, OPENAI_ORG_ID |
variable / secret | Once: creates an OpenAI integration at startup if none exists. Afterwards, /Platform/ApiIntegrations. |
SITE_EMAIL |
variable | Seeds the platform organisation’s contact email at setup (later: /Admin/OrganisationSettings), and is read on every startup as the platform’s contact address on status pages, preview-link “Report abuse” and the legal-policy placeholder — change the variable and redeploy for that. |
A pipeline variable reaches the pipeline’s steps, not the containers. A container sees only its compose file’s environment: lines and what scripts/render-deploy-env.sh writes into deploy.env; any other variable (Security__Setup__Token, Push__VapidPrivateKey, Messaging__PreviousMessageSigningKey…) silently does nothing. To pass one, add a put line to the script (put Security__Setup__Token "${SETUP_TOKEN:-}") and map the variable into the Render deploy.env step’s env: in both pipelines. What each underlying key does is in Configuration.
The two database names — set once, at first deploy
Both are optional, non-secret variables. Leave them unset unless you need them (to share a database server between deployments, say):
PLATFORM_DATABASE_NAME # default blazorblueprint-platformTENANT_DATABASE_PREFIX # default bb-org- — each organisation gets {prefix}{orgName}Every compose file passes both to every app service.
Never change these after the first deploy
TENANT_DATABASE_PREFIXnames an organisation’s database only when it is created. Changing it moves nothing; only new organisations get the new prefix.PLATFORM_DATABASE_NAMEis read at every startup. Changing it points every service at an empty platform database: every organisation and user disappears from view and/initial-setupopens again to whoever holds the setup token (see First run). Restoring the old value recovers everything.
The app checks these at startup; validate-deploy-config.sh checks the first and third before the deploy:
- The prefix is at most 23 characters and matches
^[a-z][a-z0-9_-]*$. - The prefix must not be able to compose the platform name (prefix
blazorblueprint-platplus an organisation namedform). Only the app checks this. - On PostgreSQL the platform name cannot be changed — migrations hard-code the platform schema, so the host refuses to start. MongoDB and SQL Server allow it.
Pick your database backend
Set DATABASE_TYPE to mongodb (default), postgresql or sqlserver, and the deploy uses docker-compose.yml, docker-compose.postgres.yml or docker-compose.sqlserver.yml. PostgreSQL uses one database, blazorblueprint, with a schema per tenant; SQL Server gives each tenant its own database, all with the Latin1_General_100_CS_AS_SC collation. If you create the platform or a tenant database yourself (in a cloud portal or with infrastructure-as-code), use COLLATE Latin1_General_100_CS_AS_SC; the host refuses a case- or accent-insensitive one and names the collation it needs. The images contain every backend, so switching needs no rebuild — but moving a live deployment to another backend is a data migration.
The PostgreSQL and SQL Server compose files set Database__UseMigrations=true on every service; outside Development a relational backend refuses to start without it. See Relational Schema Management.
Deploying by hand
This runs the full stack on one host with the same steps the pipeline automates.
# 1. Datastore credentials (see above) — needed by every compose command, build includedexport DATABASE_USERNAME=blazorblueprintexport DATABASE_PASSWORD=$(openssl rand -base64 32 | tr -d '+/=')export REDIS_PASSWORD=$(openssl rand -base64 32 | tr -d '+/=')
# 2. Build the images locally — or set WEB_IMAGE / APP_IMAGE / WORKER_IMAGE / MIGRATOR_IMAGE# to your registry's tags and run `pull` insteaddocker compose -f .azure/devops/docker-compose.yml build
# 3. App secrets → .azure/devops/deploy.env (the script's default output path)export WEBAPP_CLIENT_SECRET=... JWT_SECRET_KEY=... MESSAGING_SIGNING_KEY=...export DOMAIN_VERIFICATION_SECRET=...bash scripts/render-deploy-env.sh
# Optional: the bundled Grafana. The pipelines set the endpoint for you; by hand, set both# (and nothing reaches Grafana without the second line)# export COMPOSE_PROFILES=observability GRAFANA_ADMIN_PASSWORD=... # 12+ characters# export OTEL_EXPORTER_OTLP_ENDPOINT=http://blazorblueprint-grafana:4317
# 4. Gated migration, then start the stackdocker compose -f .azure/devops/docker-compose.yml run --rm blazorblueprint-dbmigratordocker compose -f .azure/devops/docker-compose.yml up -d
# Stop — never add -v in production; it deletes the volumes, the database and KEK includeddocker compose -f .azure/devops/docker-compose.yml downFor PostgreSQL or SQL Server, use docker-compose.postgres.yml or docker-compose.sqlserver.yml from the same folder. On SQL Server, leave DATABASE_USERNAME unset and export MSSQL_PID= your licensed edition. You need Docker Compose v2.24 or later for its env_file handling.
CI/CD
How the pipeline works
Azure DevOps (.azure/devops/build-pipeline.yml) and GitHub Actions (.github/workflows/build-workflow.yml) run the same flow. Both trigger on pushes and pull requests to main and develop; only main builds and deploys, while develop and pull requests run Validate (as a no-op) and Test. On GitHub, main deploys only once the DEPLOY_ENABLED repository variable is true (see GitHub Actions setup).
- Validate — runs
scripts/validate-deploy-config.shagainst your datastore credentials, so a bad value fails in seconds. It checks only onmain(and on a manual GitHub run); elsewhere it passes without checking, because fork PRs can’t read secrets. - Test (skipped on a rollback) — the whole solution, including the relational suites against PostgreSQL and SQL Server service containers; migration drift and additive-only checks;
scripts/check-lite-compose.sh; and an advisory vulnerable-package scan. It fails if fewer tests pass thanMIN_PASSED_TESTS(default 4400), if a test project passes fewer than its floor (TEST_PROJECT_FLOORS), if any PostgreSQL or SQL Server test is skipped or fewer thanMIN_RELATIONAL_TESTS(55) run, or if an integration test is skipped or fewer thanMIN_INTEGRATION_TESTS(245) pass.INTEGRATION_SKIP_ALLOWLIST(a regex of test names) excuses a skip; it ships empty — keep it so. The floors are in the Test stage’svariables:on Azure DevOps and repository variables on GitHub; raise them as your suite grows. - Build (
mainonly, never a pull request or rollback) — builds the four images (blazorblueprint-web,-internalapi,-background-worker,-dbmigrator) and pushes them tagged{VERSION}.{build}(e.g.1.0.0.2517) plus1.0.0andlatest. Bump theVERSIONfile at the repo root for a release. - Deploy — renders
deploy.env, picks the compose file fromDATABASE_TYPE, pulls the exact tag, runs the DbMigrator, thendocker compose up -d --no-build --wait --wait-timeout 300. It fails if a health-checked service isn’t healthy within five minutes, if Web doesn’t answer/healthon 8080 within a further 150 seconds, or if the InternalApi or BackgroundWorker isn’t running. On MongoDB it then runs the contract pass.
Rolling back means redeploying an earlier tag: on Azure DevOps, Run pipeline on main with the deployVersion parameter set to it (e.g. 1.0.0.2500; the default current deploys what the run builds); on GitHub, Run workflow on main with image_tag. A rollback validates, skips tests and build, and deploys only from main. It uses the current main compose files and render script, so if the release you are leaving renamed or added a setting the old version needs, revert that on main first (on GitHub you can instead re-run the deploy job of the run that built the tag).
Index changes on MongoDB: expand, then contract
The DbMigrator runs while the previous version is still serving, and a rollback runs an older migrator, so by default it only creates indexes (or replaces one whose options changed). The contract pass — the same image with --drop-orphan-indexes — drops managed indexes the release no longer declares. The pipelines run it after the health gate on an ordinary deploy only: never on a rollback, a retry or re-run, or when main has moved past the deployed commit (if that can’t be checked, it skips with a warning). Until it runs, a dropped-from-code index stays — harmless, unless the release removed a unique index to allow values it used to refuse; those writes fail until the pass runs. PostgreSQL and SQL Server change indexes through migrations instead.
If the pass failed or was skipped, run it by hand — the run’s message prints the command with the exact image — once the new version is up and you will not roll back. On the server, from the checkout the deploy used, export the same values the pipeline passes (DATABASE_USERNAME, DATABASE_PASSWORD, REDIS_PASSWORD, and PLATFORM_DATABASE_NAME / TENANT_DATABASE_PREFIX if set), then:
export MIGRATOR_IMAGE=<REGISTRY_BASE>/blazorblueprint-dbmigrator:<deployed tag, e.g. 1.0.0.2517>docker compose -f .azure/devops/docker-compose.yml run --rm blazorblueprint-dbmigrator --drop-orphan-indexesOn GitHub Actions the file is .github/workflows/docker-compose.yml. Without MIGRATOR_IMAGE, compose uses a local blazorblueprint-dbmigrator:latest, which is not the image you deployed.
Where the stages run. On Azure DevOps, Validate, Test and Build use a self-hosted pool named Default (change each pool: to vmImage: 'ubuntu-latest' for Microsoft-hosted agents); on GitHub, ubuntu-latest. Deploy runs on your server (an Environment VM resource, or a self-hosted runner). The Test agent needs Docker running Linux containers. Shell steps are bash (Git Bash on Windows), and every agent running Docker needs an account allowed to use it (docker group on Linux, docker-users / LocalSystem on Windows).
What you need
A container registry — Docker Hub, Azure Container Registry, GHCR or a private one — and a server with Docker, registered as your deploy agent or runner. Keep the repositories private: the images contain your compiled app.
Choosing your container registry
The pipeline appends /<image-name>:<tag> to REGISTRY_BASE:
| Registry | REGISTRY_BASE |
Resulting image |
|---|---|---|
| ACR | myregistry.azurecr.io |
myregistry.azurecr.io/blazorblueprint-web:1.0.0.1234 |
| GHCR | ghcr.io/your-org |
ghcr.io/your-org/blazorblueprint-web:1.0.0.1234 |
| Docker Hub | docker.io/your-user |
docker.io/your-user/blazorblueprint-web:1.0.0.1234 |
- ACR has no owner segment; GHCR and Docker Hub need the org or user segment.
- No trailing slash, and GHCR must be lowercase, or the push fails. (The GitHub workflow’s default
ghcr.io/<owner>is lowercased for you.) - On Azure DevOps
REGISTRY_BASEhas no default; Build and Deploy stop if it is unset. - Repositories are created on first push. GHCR packages default to private. Docker Hub’s free tier allows only one private repository, and the pipeline pushes four.
Azure DevOps setup
- Service connection: Project Settings → Service connections → New → Docker Registry (Docker Hub, Azure Container Registry, or Others for GHCR and the rest). Name it exactly
registry-connection— the pipeline uses that literal name. Re-point it to switch registries. For GHCR: URLhttps://ghcr.io, your GitHub username, and a PAT withwrite:packages+read:packages. - Environment: Pipelines → Environments → New →
BlazorBlueprint-Production→ Add resource → Virtual machines, then run the generated script on your server. Add an approval check for a manual gate, and an Exclusive Lock check so that two deploys queue rather than interleave (the Deploy stage declareslockBehavior: sequential, which needs that check). On GitHub, deploys are serialised by thedeploy-productionconcurrency group. - Variable group: Pipelines → Library →
BlazorBlueprint-Production, holdingREGISTRY_BASE,DATABASE_TYPE(if not MongoDB), the datastore credentials and the application secrets. Lock the secret ones. - Pipeline: New pipeline → Existing Azure Pipelines YAML →
.azure/devops/build-pipeline.yml. On the first run, approve its use ofregistry-connection. Push tomainto build and deploy.
Windows agent + Docker Desktop
The VM registration script runs the agent service as NT AUTHORITY\NETWORK SERVICE, which cannot reach Docker Desktop. In services.msc → vstsagent.* → Properties → Log On, set an account in the docker-users group and restart the service, or the deploy fails with cannot connect to the Docker daemon.
Define only the variables you use
Leave optional variables out of the group entirely. The render script treats an undefined $(VAR) as unset, so the app falls back to appsettings.json.
GitHub Actions setup
- Registry: nothing to set up for GHCR — images push to
ghcr.io/<owner>with the built-inGITHUB_TOKEN. For Docker Hub or ACR, set theREGISTRY_SERVER,REGISTRY_USERNAMEandREGISTRY_BASEvariables plus aREGISTRY_PASSWORDsecret. - Self-hosted runner: Settings → Actions → Runners → New self-hosted runner, on your server, with Docker and bash.
- Environment: Settings → Environments →
production. Add a required reviewer for a manual gate. - Secrets and variables: Settings → Secrets and variables → Actions. Passwords and keys under Secrets; everything else (
DATABASE_TYPE,DATABASE_USERNAME, the client IDs, the database names…) under Variables. - Switch deploys on: add the repository variable
DEPLOY_ENABLED=true. Until then the workflow runs tests only and never pushes images. - Deploy: push to
main.
Lite
Lite runs two services: web and a database. The job handlers and sweeps run inside the web process. The compose file sets ASPNETCORE_ENVIRONMENT=Lite, and appsettings.Lite.json supplies the single-process settings (in-process transport and cache, Web serving the plugin API, migrations on), so you don’t set them yourself.
Choose the database by choosing the file:
| File | Database | Service |
|---|---|---|
docker-compose.lite.yml |
MongoDB (the default) | mongodb |
docker-compose.lite.postgres.yml |
PostgreSQL 16, one schema per organisation | postgres |
docker-compose.lite.sqlserver.yml |
SQL Server 2022, one database per organisation | sqlserver |
export DOMAIN_VERIFICATION_TOKEN_SECRET=$(openssl rand -base64 32)export DATABASE_USERNAME=blazorblueprintexport DATABASE_PASSWORD=$(openssl rand -base64 32 | tr -d '+/=')docker compose -f docker-compose.lite.yml up -d # or docker-compose.lite.postgres.ymlFor SQL Server, leave DATABASE_USERNAME unset (the account is sa) and set your licensed edition:
export DOMAIN_VERIFICATION_TOKEN_SECRET=$(openssl rand -base64 32)export DATABASE_PASSWORD=$(openssl rand -base64 32 | tr -d '+/=')export MSSQL_PID=Express # or Standard, Enterprise, or a product keydocker compose -f docker-compose.lite.sqlserver.yml up -dRun it from a checkout of the repository: web has no image:, so compose builds it from source on the first up (use up -d --build after an upgrade). The app is published on port 8080. Pick the database at first deploy: all three files share the project name and KEK volume, so switching file later starts on an empty database; nothing moves data between backends.
Lite variables
Lite is configured entirely through environment variables exported before docker compose up, read directly by the compose file.
| Variable | Kind | Notes |
|---|---|---|
DOMAIN_VERIFICATION_TOKEN_SECRET |
secret | Required. Lite’s name for DOMAIN_VERIFICATION_SECRET. |
DATABASE_USERNAME / DATABASE_PASSWORD |
variable / secret | Required (no username on SQL Server). Fixed at first start; generate the password with the tr strip. |
MSSQL_PID |
variable | Required on SQL Server (see Datastore credentials). |
PLATFORM_DATABASE_NAME / TENANT_DATABASE_PREFIX |
variable | Optional; see The two database names. |
WEB_BIND_ADDRESS, TRUSTED_PROXY_NETWORK |
variable | Optional; see Reverse proxy and forwarded headers. On Lite nothing checks that the second is set only with WEB_BIND_ADDRESS=127.0.0.1. |
SITE_EMAIL, QUESTPDF_LICENSE_TYPE |
variable | Optional; as on the full stack. Set QUESTPDF_LICENSE_TYPE here rather than in appsettings.json — the compose file passes it even when empty. |
DATA_PROTECTION_KEK, DATA_PROTECTION_KEY_VAULT_* |
secret / variable | Optional; as on the full stack (see Application secrets). |
OTEL_EXPORTER_OTLP_ENDPOINT |
variable | Optional. Your own collector. |
COMPOSE_PROFILES, GRAFANA_ADMIN_PASSWORD, GRAFANA_PORT |
variable / secret / variable | The bundled Grafana (see Grafana on Lite). |
Put these in a .env file beside the compose file (the repository ignores it), so every later docker compose command — an upgrade from a new shell included — sees the same values. A plain docker run (the migrator below) does not read it: load it into the shell first with set -a; . ./.env; set +a.
Lite needs none of the full stack’s other secrets. The seed variables (EMAIL_*, OPENAI_*) and OAuth client ids are not forwarded: enter them in the app after initial setup (Platform → Email, Platform → API Integrations, Platform → External Sign-In).
Lite needs TLS in front
Every link the application builds is https:// on the default port, and the sign-in cookie is Secure outside Development, so a stack reached over plain http on its published port cannot sign anyone in. Put a TLS-terminating reverse proxy or tunnel in front. Plain http works only on localhost. See Configuration.
Lite has every feature of the full stack, subdomain organisations included (same requirements — see Application secrets). Lite is not Development: every production check applies.
Save the recovery key, and never rename the volumes
The KEK is on the bb_lite_kek volume and shown once at initial setup as the recovery key — save it. If the volume is lost, set DATA_PROTECTION_KEK to it (in .env) and leave it set. Lose both and every encrypted field and file is unreadable.
The Lite files pin the project name (blazorblueprint-lite) and every volume (bb_lite_kek; bb_lite_mongo_data, bb_lite_postgres_data or bb_lite_sqlserver_data; bb_lite_grafana_data), so an upgrade unpacked into a new folder still finds its data. Do not rename any of them; check with docker volume ls after an upgrade.
Lite is single-instance. Without Redis there is no shared cache, backplane or rate-limit store. To scale out, move to the full stack.
Incoming webhooks are at-most-once under Lite. A webhook is acknowledged before its handler runs, so a restart in between loses it. Payment and subscription state recover through polling sweeps; inbound email and SMS status callbacks do not.
Migrations under Lite
Lite’s compose file has no DbMigrator service.
- On a relational backend,
Database:MigrateTenantsOnStartup=truemigrates every existing tenant before serving (startup grows with the tenant count); a tenant whose migration fails is logged at Error and gets a 503 page while the others serve. To migrate yourself instead, setDatabase__MigrateTenantsOnStartup=falseon the web service and run the DbMigrator (NOTE 5 indocker-compose.lite.yml). - On MongoDB new indexes (from a plugin upgrade, for instance) are created only by the DbMigrator — run it after any plugin version change, or a new unique index goes unenforced for organisations that already had the plugin. An index existing data cannot take is logged at Error and skipped until you fix the rows and rerun it.
Build the DbMigrator from the same checkout and run it on the Lite network:
docker build -f Services/BlazorBlueprint.DbMigrator/Dockerfile -t blazorblueprint-dbmigrator .docker run --rm --network blazorblueprint-lite_default \ -e Database__DatabaseType=mongodb \ -e Database__ConnectionString="mongodb://$DATABASE_USERNAME:$DATABASE_PASSWORD@mongodb:27017/?authSource=admin" \ -e Database__PlatformDatabaseName=blazorblueprint-platform \ -e Database__TenantDatabasePrefix=bb-org- \ blazorblueprint-dbmigratorUse your own database names if you changed them. For a relational backend, also pass -e Database__UseMigrations=true and that backend’s connection string.
On MongoDB this only creates indexes. Once the upgraded stack is up and you will not go back, run it again with --drop-orphan-indexes after the image name (see Index changes on MongoDB).
Do not copy MigrateTenantsOnStartup=true to the full stack, where the tenant sweep is the DbMigrator’s job, once per deploy.
Production environment
These apply to both topologies unless a line says otherwise.
Remove the example plugin before go-live
Plugins/ExamplePlugin installs itself into every new organisation and adds public pages, an anonymous form, an anonymous live hub and an incoming webhook. Remove its line from Plugins/Plugins.props and rebuild, or set Plugins:BlazorBlueprint.Plugins.ExamplePlugin:Disabled to true on every host. See Plugins.
Infrastructure requirements
- Server: 4+ CPU cores, 8 GB+ RAM, 20 GB+ storage to start — plus about 1–1.5 GB of RAM and disk with the optional Grafana.
- Docker: Docker Engine with Compose v2.24+.
- Network: open 8080 to your reverse proxy and 80/443 on the proxy, nothing else. Do not open 8081, 3000 or the database and Redis ports.
- TLS: terminate HTTPS at a reverse proxy (Let’s Encrypt is fine); the containers listen on plain HTTP. Outside Development the app sends HSTS with ASP.NET Core’s defaults (30 days, no
includeSubDomains, nopreload) — set a longer policy at the proxy. A request carrying a proxy header (X-Forwarded-For,X-Forwarded-Proto,CF-VisitororCF-Connecting-IP) is treated as HTTPS, so OAuth redirect URIs come out ashttps://…. SetAuthentication:ForceHttpsScheme=falseonly if your proxy really serves plain HTTP.
Reverse proxy and forwarded headers
The app reads X-Forwarded-For, -Proto and -Host only from trusted proxies. Loopback is trusted by default, but a same-host proxy connecting to the published port reaches the container through the compose network’s gateway (typically 172.x.0.1), not loopback. List your proxy:
"Security": { "ForwardedHeaders": { "KnownProxies": [ "172.18.0.5" ], "KnownNetworks": [ "172.18.0.0/16" ] }}A KnownNetworks entry must be a canonical CIDR (172.18.0.0/16, not 172.18.0.5/16): one with host bits set is ignored with only a warning, leaving that proxy untrusted. Unlisted, every visitor appears to come from the proxy’s address and they share one rate-limit bucket. To check, open Account → Active Sessions (/Account/Manage/Sessions): if every session shows the same 172.x (or 192.168.65.x) address, the proxy is not trusted. Platform → Infrastructure lists the trusted proxies and networks.
Behind a Cloudflare Tunnel or other same-host proxy
When the proxy runs on the server itself — cloudflared as a host service with service: http://localhost:8080, or nginx / Caddy proxying to localhost:8080 — set both of these (pipeline variables on the full stack; exported on Lite):
| Variable | Set to | What it does |
|---|---|---|
WEB_BIND_ADDRESS |
127.0.0.1 |
Publishes 8080 to the host only, so nothing outside reaches the app except through the proxy. Unset, it is published on every interface — and Docker’s port rules bypass host firewalls such as ufw. |
TRUSTED_PROXY_NETWORK |
172.16.0.0/12 on Linux, 192.168.65.0/24 on Docker Desktop |
Trusts the Docker gateway the proxy arrives from (written to Security:ForwardedHeaders:KnownNetworks:1, keeping loopback). Only the last X-Forwarded-For entry is believed, so a visitor cannot pick their own. |
Set TRUSTED_PROXY_NETWORK only with WEB_BIND_ADDRESS=127.0.0.1 — otherwise any caller could name its own IP — and on the full stack scripts/render-deploy-env.sh refuses it unless WEB_BIND_ADDRESS is a 127.x address. Confirm the source address first: deploy with only WEB_BIND_ADDRESS=127.0.0.1, sign in through the proxy from two devices, and the shared address Account → Active Sessions shows is the one to trust (Docker Desktop’s 192.168.65.x is outside 172.16.0.0/12).
When the proxy runs as a container on the compose network (cloudflared with service: http://blazorblueprint-web:8080), it arrives from inside 172.16.0.0/12, so the same pair applies — or leave both unset and accept one shared address. A proxy container on another Docker network cannot reach a port bound to 127.0.0.1.
Firewall the app port to the proxy
Anything that reaches port 8080 directly from a trusted address can set its own client IP and protocol, bypassing rate limiting and HTTPS assumptions. Make the app reachable only through the proxy.
First run
Until the first organisation exists, every page redirects to /initial-setup for a trusted caller and to a “setup not allowed” page for anyone else. A caller is trusted if it presents the setup token, or connects from loopback (Development only) or a Security:Setup:TrustedNetworks / TrustedProxies address and uses localhost, 127.0.0.1 or [::1] as the host name. Don’t trust the Docker bridge network for setup: behind a published port every caller arrives from its gateway.
So in a container, use the setup token. Unless you set one, the app generates one on each start and logs it at Warning the first time a setup attempt is refused:
docker compose -f .azure/devops/docker-compose.yml logs blazorblueprint-web | grep setupToken # Fulldocker compose -f docker-compose.lite.yml logs web | grep setupToken # Lite (or your .postgres / .sqlserver file)Then open the address on that line — http://localhost:8080/initial-setup?setupToken=…, built from the port the app listens on; from another machine, use the same path on the address you reach the app at (also needed when setting up over a domain rather than localhost). For more than one web replica, or a scripted first run, pin it with Security__Setup__Token (at least 32 random characters; a shorter one is ignored). The token authorises nothing once an organisation exists. See Security → Initial setup.
Health checks
Every app service answers /health (readiness: the database, plus the platform organisation on Web, Redis under Full, and the stream consumers on the worker) and /alive (liveness: the process only, so a liveness probe won’t restart every container over a database outage). They answer on any host name the probe uses; only a verified customer hostname refuses them (404).
- Every app service has a compose healthcheck (every 30 s, 90 s start period), so
docker psshows its state — but compose does not act on it: restart policies react to a container exiting, not to it becoming unhealthy. Degradedanswers HTTP 200. A monitor that reads only the status code won’t notice.- The BackgroundWorker also answers
GET /health/messaging(internal port 8082): each stream consumer’s liveness, as JSON. Platform → Infrastructure probes it. - A probe never waits more than 30 seconds (then 503 Unhealthy); answers are shared and reused for up to five seconds, so hard polling adds no load.
/Platform/Infrastructure(platform admins) summarises the topology, environment, database and version, and the configuration Web is running with and where each value came from (secrets shown only as set / not set / placeholder). On the full stack it also has a live status dashboard of every service.
Observability: logs, metrics and traces
Every host — web, internal API, worker and migrator — logs to the console and, when OTEL_EXPORTER_OTLP_ENDPOINT is set, sends logs, metrics and traces over OpenTelemetry (OTLP). It is unset by default, and then nothing leaves the deployment. Both pipelines take it as a variable and every compose file hands it to every service. The endpoint is the only switch.
Console logs are one line per event (UTC timestamp, level, category, key=value scopes, message), so line-based shippers need no multi-line rules; set Logging__Console__FormatterName=json for JSON. Scopes say where a line came from — OrgId, CircuitId, JobId / JobType, Sweep — and with OpenTelemetry on, each line carries its trace id. Ids only: no names, email or IP addresses.
What is sent. Each host reports as service.name blazorblueprint-web, -internalapi, -backgroundworker or -dbmigrator (override with OTEL_SERVICE_NAME). Traces cover every request except health probes, static files and long-lived circuit/hub connections, plus outbound HTTP, database and Redis calls, circuit events, each background job (one trace from publisher to worker) and each sweep tick; URL paths go through the same redaction templates as analytics, and an outbound call to a credential-bearing URL (a webhook, a push endpoint) records only scheme and host. Metrics are ASP.NET Core, HttpClient, the .NET runtime and the application’s own meters, below (a plugin’s meter or ActivitySource under the BlazorBlueprint. prefix is exported too). Logs are every line at the configured level; audit events also go to the BlazorBlueprint.Audit category (see Security → Audit trail).
| Meter | Measures | Tags |
|---|---|---|
BlazorBlueprint.ApiUsage |
calls, failures, prompt/completion tokens and duration of every third-party call; calls the stored usage report dropped | kind, direction, provider, model, app, payer, organisation id; reason |
BlazorBlueprint.Messaging |
jobs published, executed, dead-lettered and their duration; queued jobs a caller waited on and the wait; stream length and pending | stream, job type, outcome |
BlazorBlueprint.BackgroundServices |
sweep ticks and duration, organisations a sweep failed on, each sweep’s last success and interval | sweep, outcome |
BlazorBlueprint.Email |
what the outbox did with each message | outcome |
BlazorBlueprint.Webhooks |
outgoing delivery attempts, incoming calls | provider, scope, outcome |
BlazorBlueprint.Health |
each health check’s last result (2 Healthy, 1 Degraded, 0 Unhealthy) and duration | check |
BlazorBlueprint.Billing |
subscription status changes, platform payment ledger events | from, to; event, provider |
BlazorBlueprint.Plugins |
plugins registered and failed, surfaces the access gate refused | plugin, state, verdict, surface |
BlazorBlueprint.Domains |
customer hostname changes | transition |
BlazorBlueprint.Cache |
cache lookups and misses | policy |
BlazorBlueprint.Security |
requests refused by the app’s own rate-limit guards; the KEK’s source, the Data Protection key count and the newest key’s age | guard; kek |
BlazorBlueprint.Audit |
audit events | trail, action |
Rare-event counters are exported at 0 when each host starts, so increase() sees the first event after a deploy. Health checks are logged when they change (Warning when worse, Information on recovery), not on every run.
Only API usage is tagged by organisation. Each application metric is capped at Telemetry:MaxSeriesPerMetric (default 2,000) tag combinations, beyond which new ones fold into an overflow series and totals stay right. All traces are kept (Telemetry:TraceSampleRatio, default 1); lower it on every host if trace storage costs too much. The web host starts a new trace for every request and ignores a caller’s traceparent.
Where to send it
- The bundled Grafana (Full and Lite) — below.
- Your own stack (Grafana Cloud, Datadog, Azure Monitor, Honeycomb, an OpenTelemetry Collector): set
OTEL_EXPORTER_OTLP_ENDPOINT, plus the secretOTEL_EXPORTER_OTLP_HEADERSfor a vendor API key — the render step writes it intodeploy.env(on Lite, add it to the web service’senvironment:). Import the dashboards fromdeploy/grafana/dashboards/. - Splunk: point
OTEL_EXPORTER_OTLP_ENDPOINTat the Splunk Distribution of the OpenTelemetry Collector, or collect console output with a forwarder or the Docker Splunk logging driver.
The Infrastructure page shows whether export is on and where it goes. Logs carry ids rather than personal data, but check what your own plugins log before sending it to a third party.
Optional Grafana dashboards
Both topologies can run Grafana beside the app, with dashboards and alert rules ready. It is off unless switched on: from the pipeline on the full stack (variables below), from the command line on Lite (see Grafana on Lite).
Dashboards: Overview (start here: health, traffic, errors, job backlog, failing sweeps, a 7-day error budget against 99.5%, latest errors; deploys marked), Service Health, Blazor & Real-time (SignalR transport other than WebSockets means a proxy is stripping the upgrade), Dependencies, Messaging & Jobs, Background Sweeps, Email, Webhooks & Payments, Billing & Subscriptions, Security & Sign-in, Tenants, Platform, API Usage and Logs & Traces.
Alert rules (deploy/grafana/provisioning/blazorblueprint-alerts.yaml, labelled severity critical, warning or info) cover host and health-check failures, mixed versions, plugin load failures, Data Protection key rotation and key-ring errors, error-budget burn and server errors, circuit crashes, organisations held at 503, dead letters, job failures and backlogs, failing or stopped sweeps, abandoned email, disputed payments, past-due bursts, demoted hostnames, password guessing and operator changes — plus a Watchdog that always fires, on purpose.
No contact point is configured, so nothing notifies until you add one (Alerting → Contact points) and point the default notification policy at it. Route the Watchdog (alertname = Watchdog) to a dead-man’s switch such as healthchecks.io, and keep an external uptime check on /health — Grafana runs on the same server and cannot report it going down. Don’t provision a contact point from an environment variable that may be empty: an empty one stops Grafana starting.
Dashboards and rules are read-only in the UI; change the file and redeploy.
| Variable | Kind | |
|---|---|---|
GRAFANA_ENABLED |
variable | true to run it. Blank or false leaves it off — and stops one an earlier deploy started. Anything else fails validation. |
GRAFANA_ADMIN_PASSWORD |
secret | Required while GRAFANA_ENABLED=true, at least 12 characters; without it the deploy stops before changing anything, and the container refuses to start rather than fall back to admin/admin. Sign in as admin. Applied on first start only; reset it inside Grafana afterwards. |
GRAFANA_PORT |
variable | Optional. Host port, default 3000. |
- It is reachable only from the server itself (
127.0.0.1:3000). Use an SSH tunnel (ssh -L 3000:localhost:3000 you@server) or a reverse proxy with its own sign-in; never publish it openly — it shows organisation ids and every provider the deployment calls. Anonymous access is off. - Telemetry is pointed at it automatically while
OTEL_EXPORTER_OTLP_ENDPOINTis blank; set that yourself and the bundled Grafana receives nothing. - It is one container (
grafana/otel-lgtm), which Grafana publishes for development, demo and testing — no high availability. Metrics and logs are kept 15 days, traces 14, in thegrafana_datavolume. For production monitoring, prefer your own stack. - Dashboards and rules are files in this repository (
deploy/grafana/dashboards/*.json,deploy/grafana/provisioning/), loaded on every start. - To try them locally, run the Aspire AppHost: every launch profile except
AppHost (Lite)starts this image (toggle withGrafana__Enabled; with it off,BB_OTLP_ENDPOINTnames another collector). See Getting Started.
Grafana on Lite
Every Lite file carries the same Grafana service under the compose profile observability. Switch it on with the COMPOSE_PROFILES variable, not the --profile flag — the flag starts Grafana but does not point the app’s telemetry at it. Put both values in .env beside the compose file:
COMPOSE_PROFILES=observabilityGRAFANA_ADMIN_PASSWORD=<a strong password>docker compose -f docker-compose.lite.yml up -d # or your .postgres / .sqlserver fileExported in the shell instead, a later up from a shell without COMPOSE_PROFILES recreates web with no telemetry endpoint and the dashboards quietly stop updating. Telemetry goes to Grafana automatically while OTEL_EXPORTER_OTLP_ENDPOINT is blank. GRAFANA_ADMIN_PASSWORD is required however Grafana was switched on (the container exits without it) and applies on first start only. Access rules are as above; data lives in bb_lite_grafana_data.
-
To switch it off, remove
COMPOSE_PROFILES, then remove the container and recreate web (a plainupleaves a running Grafana in place):Terminal window docker compose -f <your Lite file> --profile observability rm --stop --force blazorblueprint-grafanadocker compose -f <your Lite file> up -d -
The panels about Redis streams, the BackgroundWorker and the InternalApi stay empty on Lite.
Backups
| Full | Lite | |
|---|---|---|
| Encryption keys | in the database | in the database |
| Key-encrypting key | bb_kek (and the recovery key, saved at setup) |
bb_lite_kek (and the recovery key, saved at setup) |
| Database | mongodb_data / postgres_data / sqlserver_data |
bb_lite_mongo_data / bb_lite_postgres_data / bb_lite_sqlserver_data |
| Dashboards history (only while Grafana is on) | grafana_data |
bb_lite_grafana_data |
- Back up the database, off the server. It holds the encryption keys with the data, so they are always restored together. A restore that brings back organisations without the key ring stops the app starting rather than letting it begin a new one (see
DataProtection:AllowDiscriminatorChangein Configuration). With Azure Blob or S3 storage, back up the bucket too; its encrypted files need the database’s key ring. - Keep the recovery key (password manager plus one offline copy). It replaces the KEK volume if lost; the volume itself needs no backup.
- A VM snapshot captures every volume, KEK included — guard snapshots like the server. See Security → Encryption keys.
- Never run
docker compose down -vordocker volume rmon these volumes in production. Caching:RedisKeyPrefixnamespaces everything this deployment keeps in Redis. Set it once at first deploy, the same on every host.
Scaling out to multiple instances
The shipped compose files run everything on one node, which scales vertically a long way. To go further, run several app instances behind a load balancer against one shared data tier: in a copy of the compose file, remove the database and Redis services (and their depends_on entries) and point each service’s Database__ConnectionString and ConnectionStrings__redisCache at the shared tier.
- Redis must be shared — backplane, caches and job streams.
- Every instance needs the same KEK. Machines cannot share the
bb_kekvolume, so set the sameDATA_PROTECTION_KEKeverywhere (the recovery key, or one generated before first start), or use one Azure Key Vault key. - Use sticky sessions for Web — each circuit lives in one instance’s memory. The InternalApi needs none: a Web instance dials its hubs straight to a WebSocket, with no negotiate request to land on another instance, and sends cross between instances over the Redis backplane. A load balancer in front of it must pass WebSockets.
- The Web → InternalApi hop is plain HTTP (
http://blazorblueprint-internalapi:8081), carrying the client secret to/api/token, the service JWT on every call and, for hubs the InternalApi serves, hub tokens and everything those hubs carry, message text included. On one host it stays on the compose network; across machines, keep it on a private network or put TLS in front and pointServices__InternalApi__Urlathttps://…. - Prefer a single BackgroundWorker. Queue consumers share work safely, but every recurring sweep runs in every worker replica. The built-in sweeps that send, charge or count each guard against running twice; a plugin’s sweep is safe only if its author added such a guard.
- Use identical
Messaging:MessageSigningKeyandCaching:RedisKeyPrefixon every host. A mismatch gives no error, just jobs that never run. Rotate the signing key withMessaging:PreviousMessageSigningKey(see Configuration). - Migrate once per deploy, before rollout, not per instance.
- Make the database redundant too: a MongoDB replica set, or a PostgreSQL / SQL Server primary with replicas.