07 — Platform runbook
Version: 2.7
Last Updated: 2026-08-03 20:31:46
Location: docs/04 - OPERATIONS/ — local dev, optional Docker rehearsal, and live VPS day-2 procedures
Who this is for: Anyone running LynCareOS day to day — dev startup, troubleshooting, VPS logs/restarts/backups — including the AI coding assistant.
Not for first-time deploy. Shipping a new release → 03 - DEPLOYMENT AND PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md.
Treat each section as a checklist. Work top-to-bottom.
Production (live subscribers) runs on DigitalOcean VPS
lyncareos-prod-syd1. Deploy / release: 20-PRODUCTION-DEPLOYMENT-GUIDE §2a — dev test → Docker UAT gate (code + migrations) → VPS (push-to-production.ps1, agent-run). Day-2 on the VPS: §12–§17 below. Daily feature work: development stack (§3,lyncareos_dev). Optional Docker full-stack detail: §7.
Table of Contents
Section titled “Table of Contents”- Architecture overview
- Prerequisites
- Development — Startup
- Development — Shutdown
- Troubleshooting dev environment
- Building Docker images
- Running full-stack in Docker
- Production environment variables
- Cloudflare Tunnel — connectivity reference
- Database migrations (safe workflow)
- Useful one-liners
- Production (operations host) — daily operations
- App image roll — command reference (deploy is doc 20)
- Production (operations host) — Cloudflare Tunnel management
- Production (operations host) — backups & restore drill
- Production (operations host) — incident response
- Production (operations host) — common one-liners
- PostgreSQL collation — REINDEX after VPS OS upgrade
1. Architecture overview
Section titled “1. Architecture overview”⚠️ Production vs development (proxy UAT) vs optional Docker rehearsal
Section titled “⚠️ Production vs development (proxy UAT) vs optional Docker rehearsal”For assistants and operators: this project does not use a separate, dedicated UAT machine or environment. Pre-production testing and “UAT”-style checks are done with the development stack (§3): Vite, FastAPI on 8021, database lyncareos_dev on native Postgres — that is the primary non-production path. Do not plan or provision a second “UAT environment” as a default; only add full-stack Docker (below) when you explicitly need a production-shaped container run.
Live production (subscribers, real data) runs on the DigitalOcean VPS — see 03 - DEPLOYMENT AND PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md for deploy and §12–§17 in this document for day-2 ops.
On a developer workstation you can run two PostgreSQL-related paths; the first row is the usual non-production workflow (dev-as-proxy-UAT):
| Primary: development (proxy UAT) | Optional: full-stack Docker (rehearsal / prod-shaped) | |
|---|---|---|
| Instance | Native Windows postgres.exe (or your dev DB on 5432) | Docker lyncareos-postgres-1 |
| Data volume | Native install / lyncareos_dev | Docker named volume lyncare_pg_data |
| How to connect | psql -U lyncare -h localhost -p 5432 | docker exec … psql … or GUI to 127.0.0.1:5433 (default published port) |
| Backend | Local FastAPI on 8021 (§3) | app container (Compose production profile) on localhost:8020 (§7) |
| Role | Day-to-day work and integration-style testing before production; this is the stand-in for a separate UAT tier | Use when you need a built SPA + same image shape as production; not required for routine validation |
Rule: Never use
docker compose down -vwhen thelyncare_pg_datavolume has data you care about (optional Docker DB) —-vdeletes the volume. For disposable resets,-vis fine.
Rule: From Windows,
localhost:5432usually hits native dev Postgres, not the Docker container (Docker is typically on 5433). Verify host/port before running DDL.
Where live production data lives
Section titled “Where live production data lives”| Production (operations host) | Non-production (not a second “UAT server”) | |
|---|---|---|
| URL | https://app.lyncareos.com via Cloudflare Tunnel → localhost:8020 on that host | Default: Vite + API — http://localhost:5173 → 8021 (dev / proxy UAT). Optional: http://localhost:8020 if you started full-stack Docker (§7). |
| Operator access | PowerShell on the same machine: repo root → docker compose --env-file .env.production --profile production … | dev-start.ps1 / §3 for daily work; optional docker compose … --profile production from repo root for container rehearsal only |
| Runbook | §12–§17 | §3–§5 (dev); §6–§7 (optional Docker) |
DATABASE_URL is the only switch — dev cannot “accidentally” stay safe
Section titled “DATABASE_URL is the only switch — dev cannot “accidentally” stay safe”The backend does not read a separate “environment badge” to decide whether it is allowed to hit production. DATABASE_URL alone determines which PostgreSQL instance and database receive logins, API writes, seed scripts, and python -m migrations.runner. There is no application-level block on connecting a developer workstation to a production host if someone pastes that DSN into backend/.env or exports it in the shell.
Non-negotiable:
- Never put a production PostgreSQL URL (production hostname, production VPC address, or tunnel endpoint to prod) in
backend/.envon a machine used for Vite /npm run devor casual testing. That configuration makes the local dev server API talk to live data whenever the proxy points at it (VITE_API_URL), or whenever you run the backend locally with that file. - Never run
migrations.runneror manual DDL against a DSN you have not explicitly verified (host, port, database name). A typo or a copied-from-prod.envcan apply migrations to the wrong cluster. - Prefer separate files for production-only secrets (e.g.
backend/.env.productiononly on the server, gitignored) and keep devDATABASE_URLpointed at local or explicitly non-production databases (Docker Postgres onlocalhostwith a published port such as 5433, or native Postgres on 5432 — see Architecture overview).
See also 11 — Hard rules: which database you are touching.
VITE_API_URL is the second switch — and equally dangerous
Section titled “VITE_API_URL is the second switch — and equally dangerous”VITE_API_URL in frontend/.env controls which backend the Vite dev server proxies /api/* to. It is a direct line to whatever database that backend uses.
VITE_API_URL value | Backend | Database |
|---|---|---|
http://localhost:8021 | Local FastAPI (dev) | lyncareos_dev (port 5432) — correct for dev and proxy-UAT work |
http://localhost:8020 | Docker app on this PC (only if you started §7 stack) | lyncareos via Docker Postgres — optional rehearsal data unless this PC is the production host (then it is live) |
**Setting VITE_API_URL=http://localhost:8020 sends the Vite dev UI to the local Docker backend and its lyncareos database. You can still damage that database (invites, test tenants); do not treat it as a throwaway sandbox unless you meant to wipe it.
Rule: frontend/.env must use VITE_API_URL=http://localhost:8021 for normal development and pre-production validation (proxy UAT). Port 8020 is only when you deliberately point the Vite UI at the optional full-stack Docker app (§7).
Live production is at https://app.lyncareos.com — the browser talks to that stack directly when you test the real site; it is not selected by localhost in VITE_API_URL.
Verify before every dev session:
Get-Content frontend\.env | Select-String VITE_API_URL# Must show: VITE_API_URL=http://localhost:8021Restart the Vite dev server after any change (Vite reads .env at start-up, not live).
Docker Postgres from a Windows GUI (DBeaver, etc.): Compose publishes the container on a different host port than 5432 so it does not clash with native PostgreSQL. Default in docker-compose.yml is 5433:5432 (host port : container port — Postgres still listens on 5432 inside the container). Connect with 127.0.0.1, port 5433, database lyncareos, user/password from POSTGRES_*. Override the host port with env POSTGRES_HOST_PORT (e.g. 5472) in the same directory as docker compose if you need a specific number.
┌─ Development (primary non-prod — proxy UAT) ───────────────────────────────┐│ Browser → Vite dev server :5173 → proxy /api → FastAPI :8021 (Windows) ││ │ ││ localhost:5432 ││ Native Windows PostgreSQL ││ (lyncareos_dev — not production) ││ No separate UAT environment is required; validate here before production. │└──────────────────────────────────────────────────────────────────────────┘
┌─ Optional: full-stack Docker on this PC (§7 — prod-shaped rehearsal) ──────┐│ Browser → http://localhost:8020 → FastAPI app container :8020 ││ │ /api/* → API ││ │ /* → React SPA from /dist ││ │ ││ postgres:5432 (Docker internal network) ││ Docker PostgreSQL — lyncare_pg_data (only if you use §7) │└──────────────────────────────────────────────────────────────────────────┘
┌─ Production (DigitalOcean Sydney VPS — see §12) ────────────────────────────┐│ Browser → https://app.lyncareos.com (Cloudflare Tunnel c0396e69) ││ → cloudflared systemd on lyncareos-prod-syd1 (134.199.173.206) ││ → http://127.0.0.1:8020 → Docker: app + pgbouncer + postgres + redis││ Postgres data: 50 GB DigitalOcean block volume at /data/pg │└────────────────────────────────────────────────────────────────────────┘In development the Vite dev server (port 5173) provides hot-module reloading and proxies all /api/* calls to the FastAPI backend on port 8021 which connects to the native Windows PostgreSQL (lyncareos_dev). This is the default “UAT” stand-in for this project — not a second deployed environment.
Optional: with Compose production profile on a non-production machine, the React app is pre-built (npm run build) and FastAPI serves frontend/dist on port 8020 (§7). Production uses the same docker-compose.yml and same profile on the operations host; the only difference is which machine and which volume hold authoritative data.
2. Prerequisites
Section titled “2. Prerequisites”| Tool | Min version | Check |
|---|---|---|
| Docker Desktop | 4.x | docker --version |
| Docker Compose | v2 (bundled with Docker Desktop) | docker compose version |
| Python | 3.12 | python --version |
| Node.js | 20+ | node --version |
| npm | 9+ | npm --version |
Python venv must be created once before first use:
cd backendpython -m venv venvvenv\Scripts\pip install -r requirements.txtNode modules must be installed once:
cd frontendnpm install3. Development — Startup
Section titled “3. Development — Startup”Option A — Automated (recommended)
Section titled “Option A — Automated (recommended)”Run the startup script from the project root:
.\dev-start.ps1This does all three steps below in sequence and waits for each service to be healthy before proceeding.
Option B — Manual (step by step)
Section titled “Option B — Manual (step by step)”Step 1 — Verify native Windows PostgreSQL is running
Section titled “Step 1 — Verify native Windows PostgreSQL is running”Dev uses the native Windows PostgreSQL service on localhost:5432. There is no Docker postgres for dev.
# Confirm the native Windows PG service is runningGet-Service -Name postgresql*
# Test connectivity (expects "1" as output)psql -h localhost -p 5432 -U lyncare -d postgres -c "SELECT 1" -tAIf the service is stopped, start it via Windows Services (services.msc) or:
Start-Service postgresql*Ensure lyncareos_dev database exists (only needed once):
psql -h localhost -p 5432 -U lyncare -d postgres -c "CREATE DATABASE lyncareos_dev OWNER lyncare;" 2>$nullDo not run
docker compose up -d postgresfor dev. That starts the production Docker postgres container.
Step 2 — Start the FastAPI backend
Section titled “Step 2 — Start the FastAPI backend”Windows requirement: uvicorn must use
--loop asyncioon Windows. The--loop asyncioflag forcesSelectorEventLoop, which psycopg requires. Without it, psycopg raisesPsycopg cannot use the 'ProactorEventLoop'and the server starts but cannot execute any database queries.
Critical: always clear
DATABASE_URLfrom the shell session before starting the server. Test runs setDATABASE_URL=…_testin the process environment; if that variable is inherited by uvicorn, it silently connects to the empty test database and all logins return 401.
Critical: kill any stale backend processes first. Leftover Python processes from earlier sessions (e.g. after a crash, a PowerShell close without Ctrl-C, or running
dev-start.ps1multiple times) will still hold port 8021 and answer requests — using old code. The new uvicorn process will still start (with multiple PIDs appearing in netstat) but you cannot tell which instance is serving a given request. Always clear the port before starting.
# 0. Kill any stale backend processes on port 8021$stalePids = (netstat -ano | Select-String ":8021 .*LISTENING") | ForEach-Object { ($_ -split '\s+')[-1] } | Sort-Object -Uniqueif ($stalePids) { Write-Host "Killing stale PIDs: $stalePids" $stalePids | ForEach-Object { taskkill /PID $_ /F /T 2>&1 | Out-Null } Start-Sleep -Seconds 2}
# 1. Clear stale env vars from any previous test runs$env:DATABASE_URL = $null$env:TEST_DATABASE_URL = $null
cd backend.\venv\Scripts\python.exe -m uvicorn main:app ` --host 127.0.0.1 ` --port 8021 ` --loop asyncio ` --reloadExpected output:
INFO: Application startup complete.Verify: http://localhost:8021/api/docs — should return the Swagger UI (HTTP 200).
Step 3 — Start the Vite frontend dev server
Section titled “Step 3 — Start the Vite frontend dev server”cd frontendnpm run devExpected output:
VITE ready in xxx ms ➜ Local: http://localhost:5173/The browser tab opens at http://localhost:5173.
Service URLs (development)
Section titled “Service URLs (development)”| Service | URL |
|---|---|
| Frontend (React) | http://localhost:5173 |
| Backend API | http://localhost:8021 |
| Swagger / API docs | http://localhost:8021/api/docs |
| PostgreSQL (dev) | Native Windows PostgreSQL localhost:5432, database lyncareos_dev |
Credentials (development)
Section titled “Credentials (development)”| Item | Value |
|---|---|
| App login username | Peter |
| App login password | See backend/.env → ADMIN_PASSWORD |
| DB — dev / proxy UAT (native Windows PostgreSQL) | host localhost:5432, db lyncareos_dev, user/pass lyncare/lyncare |
| DB — optional Docker rehearsal (only if §7 stack is running) | docker exec lyncareos-postgres-1 psql -U lyncare -d lyncareos (or host port 5433) |
| DB — production (operations host) | docker compose --env-file .env.production --profile production exec postgres psql -U lyncare -d lyncareos — see §12 |
Important:
localhost:5432from Windows reaches native Windows PostgreSQL when installed — not the Docker Postgres container. Compose publishes Docker Postgres on a different host port (default5433).backend/.env→DATABASE_URLmust use the same port you intend; a mismatch (e.g. app on 5432 while Docker listens on 5433) is wrong DB or no DB — and must never be “fixed” by pasting a cloud productionDATABASE_URLinto a dev machine. See Architecture overview.
4. Development — Shutdown
Section titled “4. Development — Shutdown”Option A — Automated
Section titled “Option A — Automated”.\dev-stop.ps1Option B — Manual
Section titled “Option B — Manual”# Kill backend (Ctrl-C in its terminal, or:)Stop-Process -Id (Get-Content .backend.pid) -Force
# Kill frontend (Ctrl-C in its terminal, or:)Stop-Process -Id (Get-Content .frontend.pid) -Force
# Stop PostgreSQL (data is preserved in the Docker volume)# Native Windows PostgreSQL is always-on; do not stop it.# Do NOT run docker compose stop postgres — that stops the production container.
To also **delete** the PostgreSQL data volume (full reset):
```powershelldocker compose down -v5. Troubleshooting dev environment
Section titled “5. Troubleshooting dev environment”Local UI appears to show “real” production patients or wrong data
Section titled “Local UI appears to show “real” production patients or wrong data”Symptom: After changing backend/.env or VITE_API_URL, the app shows data you only expect on the public site.
Cause: The browser talks to whichever backend URL the Vite proxy uses; that backend’s DATABASE_URL selects the database. If it points at production (or a copy of it), or at the optional Docker lyncareos DB (8020) when you thought you were on dev (lyncareos_dev / 8021), you are not in the database you expect.
Fix: Remove cloud production DSNs from dev machines. Set DATABASE_URL to lyncareos_dev for daily dev (correct host port). Restart backend and Vite. See DATABASE_URL is the only switch and 00-INDEX.md — Terminology.
Dev browser shows wrong-tenant data / invite links show wrong patient / API returns stale responses
Section titled “Dev browser shows wrong-tenant data / invite links show wrong patient / API returns stale responses”Symptom: Changes made in the UI create records in the wrong database, invite links are missing patient names that were just added, or the API returns responses that don’t match what the code should produce.
Most likely cause A — VITE_API_URL points at port 8020 (optional full-stack Docker, not 8021 dev):
Get-Content frontend\.env | Select-String VITE_API_URLIf the value is http://localhost:8020, the dev frontend is talking to the optional Docker full-stack app (§7), not the dev API (proxy UAT). Fix:
# In frontend/.env — change to:# VITE_API_URL=http://localhost:8021# Then restart the Vite dev server.Most likely cause B — Stale backend processes running old code on port 8021:
Multiple Python processes from different times of day can all be listening on port 8021 simultaneously (because run_server.py uses multiprocessing workers). The OS distributes connections across all of them. A process started at 9 AM will serve requests with the code snapshot from 9 AM — ignoring every code change made since. Symptoms include API responses missing fields that were just added, or endpoints returning data from the wrong database.
Diagnose:
netstat -ano | findstr ":8021 " | findstr LISTENING# More than one PID = stale processes presentGet-Process | Where-Object { $_.Name -match "python" } | Select-Object Id, StartTime, CommandLine | Format-ListFix — kill everything on the port, then start fresh:
$pids = (netstat -ano | Select-String ":8021 .*LISTENING") | ForEach-Object { ($_ -split '\s+')[-1] } | Sort-Object -Unique$pids | ForEach-Object { taskkill /PID $_ /F /T 2>&1 | Out-Null }Start-Sleep -Seconds 3# Then restart the backend (Step 2 above)502 Bad Gateway in the browser
Section titled “502 Bad Gateway in the browser”The Vite proxy forwards /api/* to the backend. A 502 means the backend is not running.
# Confirm port 8021 is not listeningnetstat -ano | Select-String ":8021.*LISTENING"
# Restart backend (Steps 2 above)401 Invalid credentials on every login
Section titled “401 Invalid credentials on every login”Almost always caused by DATABASE_URL pointing to the test database.
# Confirm which database the server is using$env:DATABASE_URL # should be blank or postgresql://...lyncareos_dev (not lyncareos_test)
# Fix: clear the variable and restart the backend$env:DATABASE_URL = $null$env:TEST_DATABASE_URL = $null# Then restart uvicorn401 when logging in with email (username still works) after PHI encryption
Section titled “401 when logging in with email (username still works) after PHI encryption”Cause: Login looks up users by email_idx (HMAC blind index). If PHI_BLIND_INDEX_KEY / PHI_ENCRYPTION_KEY were pinned in backend/.env after rows were encrypted with HKDF-from-SECRET_KEY, the stored email_idx no longer matches the address you type — email login returns 401 even with the correct password. Username login (lower(username) = …) still works when password_hash is valid.
Fix (super-admin / known email in .env):
cd backendpython seed_admin.py # updates by ADMIN_EMAIL or ADMIN_USERNAME; refreshes email_enc + email_idxFix (all decryptable users):
cd backendpython -m migrations.scripts.repair_phi_email_indexesLegacy rows (enc_version = 0, empty email_enc): These accounts never received an email blind index (common after V091 dropped users.email before backfill). Use username only, or re-invite / reset the account.
Diagnose (no secrets printed):
cd backendpython tools/diagnose_login_phi.py# Release gate (counts only) — also used by push-to-production / deploy:# .\scripts\verify-phi-crypto-health.ps1 -Target DockerUat|VpsSee 11-DATABASE-SAFETY-AND-MIGRATIONS.md §2a-gate for the hard release gate.
psycopg ProactorEventLoop error (Windows only)
Section titled “psycopg ProactorEventLoop error (Windows only)”Psycopg cannot use the 'ProactorEventLoop'You forgot --loop asyncio. Stop the server and restart with that flag.
Backend starts but /api/docs returns 500
Section titled “Backend starts but /api/docs returns 500”Check the backend log for a startup error. Most common cause is DATABASE_URL not set or PostgreSQL not running.
# Is Postgres running?docker compose ps# If not:docker compose up -d postgresDatabase schema is out of date
Section titled “Database schema is out of date”init_db() runs on every startup and applies backend/schema.sql — this is idempotent (CREATE TABLE IF NOT EXISTS). Simply restart the backend to pick up schema changes.
6. Building Docker images
Section titled “6. Building Docker images”The Dockerfile lives at backend/Dockerfile. It is a two-stage build:
- Stage 1 (
build-frontend): Node 22, runsnpm ci && npm run build, producesfrontend/dist. - Stage 2 (
app): Python 3.12-slim, installs Python requirements, copies backend code and the built frontend dist.
The resulting image contains the full application — both the API and the React SPA.
Build the image
Section titled “Build the image”Run from the project root (where .dockerignore lives):
docker build \ -f backend/Dockerfile \ -t lyncareos:latest \ .Tag for a specific release:
docker build -f backend/Dockerfile -t lyncareos:1.0.0 .Inspect the build
Section titled “Inspect the build”# Check image sizedocker images lyncareos
# Start a shell in the image for inspectiondocker run --rm -it lyncareos:latest /bin/bashTag and push to a container registry
Section titled “Tag and push to a container registry”Replace <registry> with your registry host (e.g. Docker Hub, AWS ECR, Cloudflare, GitHub Container Registry):
docker tag lyncareos:latest <registry>/lyncareos:latestdocker push <registry>/lyncareos:latest7. Running full-stack in Docker
Section titled “7. Running full-stack in Docker”Relationship to §3: this section is not the default non-production workflow. Proxy UAT happens in the development stack (Vite + 8021 + lyncareos_dev). Use full-stack Docker here only when you need a production-shaped run (built SPA in the image, same Compose profile as live) on a machine that is not serving app.lyncareos.com as production, or when debugging container-only issues.
The docker-compose.yml has a production profile. Services in this profile (app) are only started when you explicitly enable it.
Create a production environment file
Section titled “Create a production environment file”cp backend/.env backend/.env.productionEdit backend/.env.production — set at minimum:
ENVIRONMENT=productionSECRET_KEY=<64-char random hex> # python -c "import secrets; print(secrets.token_hex(32))"ALLOWED_ORIGINS=https://yourdomain.comPOSTGRES_USER=lyncarePOSTGRES_PASSWORD=<strong-password>POSTGRES_DB=lyncareosStart the full stack
Section titled “Start the full stack”The app service loads backend/.env (env_file) so SECRET_KEY, ALLOWED_ORIGINS, and other settings match local dev. Compose overrides ENVIRONMENT=production and DATABASE_URL to use the postgres container. Without a real SECRET_KEY in that file, workers crash-loop and the site will not load.
# Start postgres + app (uses backend/.env for secrets)docker compose --profile production up -dFor a dedicated production env file instead:
docker compose --env-file backend/.env.production --profile production up -dEnsure that file defines SECRET_KEY and ALLOWED_ORIGINS (and matches your DB credentials if you override Postgres).
Services started:
| Service | Container port | Host port (default) |
|---|---|---|
postgres | 5432 | 5433 (POSTGRES_HOST_PORT, maps to container 5432) |
app | 8020 | 8020 |
Open http://localhost:8020 — the React app is served directly by FastAPI.
View logs
Section titled “View logs”docker compose logs -f appdocker compose logs -f postgresdocker compose --profile production down# Add -v to also delete the database volume (DESTRUCTIVE)Update to a new version
Section titled “Update to a new version”# Rebuild image with latest codedocker build -f backend/Dockerfile -t lyncareos:latest .
# Rolling restart (Compose recreates the container, Postgres keeps running)docker compose --env-file backend/.env.production --profile production up -d --no-deps appStop production, rebuild the app image, keep the database
Section titled “Stop production, rebuild the app image, keep the database”Use this when you want a fresh app image from the repo but must not reset PostgreSQL data (no down -v, no new volume).
-
Stop the stack (containers removed; named volume
lyncare_pg_datais kept):Terminal window docker compose --profile production downIf you use a production env file for secrets:
Terminal window docker compose --env-file backend/.env.production --profile production down -
Rebuild only the application image (frontend build + Python stage):
Terminal window docker compose --profile production build app -
Start again (Postgres comes back with the same data;
appuses the new image):Terminal window docker compose --profile production up -dOr with env file:
Terminal window docker compose --env-file backend/.env.production --profile production up -d
You do not need to “rebuild the database” or re-seed: the Docker volume is unchanged unless you run down -v or delete the volume manually.
If you only want to build the image (e.g. for docker push) and leave containers stopped, run steps 1–2 and skip step 3.
8. Production environment variables
Section titled “8. Production environment variables”All configuration is injected at runtime via environment variables. The backend/.env file is never baked into the Docker image (it is in .dockerignore).
| Variable | Required | Description |
|---|---|---|
ENVIRONMENT | yes | Set to production. Enables strict checks for missing vars. |
SECRET_KEY | yes | 64-char hex string. Sign JWT tokens. Never reuse between environments. |
DATABASE_URL | yes | PostgreSQL DSN: postgresql://user:pass@host:port/db — this is the sole DB selector; wrong host = wrong data (see §1) |
ALLOWED_ORIGINS | yes | Comma-separated list of allowed CORS origins, e.g. https://app.lyncareos.com |
POSTGRES_USER | compose only | DB username (used by Compose to create the DB). |
POSTGRES_PASSWORD | compose only | DB password. |
POSTGRES_DB | compose only | DB name. |
ACCESS_TOKEN_EXPIRE_HOURS | no | Default: 8 |
REFRESH_TOKEN_EXPIRE_DAYS | no | Default: 30 |
GOOGLE_CLIENT_ID | no | Enables Google OAuth login if set. |
DB_POOL_MIN | no | Minimum pool connections. Default: 2 |
DB_POOL_MAX | no | Maximum pool connections. Default: 10 |
Generate a strong SECRET_KEY:
python -c "import secrets; print(secrets.token_hex(32))"9. Cloudflare Tunnel — connectivity reference
Section titled “9. Cloudflare Tunnel — connectivity reference”First-time production deploy (VPS + Tunnel + Pages) → 03 - DEPLOYMENT AND PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md. This section covers tunnel connectivity and legacy workstation notes.
LynCareOS uses Cloudflare Tunnel (cloudflared) for internet exposure. No public IP, no open firewall ports, no TLS certificate management — Cloudflare handles all of it. The same tunnel config works whether you’re running on this dev machine or a cloud VPS.
Internet (HTTPS) → Cloudflare Edge (lyncareos.com — proxied CNAME) → cloudflared tunnel (lyncareos / c0396e69-b202-48eb-a3c7-925b0d7c618c) → http://localhost:8020 (Docker app container) → postgres container (internal Docker network)Cloudflare Zero Trust — Access Application
Section titled “Cloudflare Zero Trust — Access Application”| Item | Value |
|---|---|
| App name | LynCareOS |
| App ID | a3b5a0f0-89a3-48d8-a145-849dc357a899 |
| AUD token | 31ac261f16409f2a6eb58bc1e514a9e716240b445b418265b16193f11b0ed7d1 |
| Domains | lyncareos.com/*, www.lyncareos.com/* |
| Policy | Bypass — everyone (app handles its own JWT auth) |
| Session | 168h |
| Interstitial | Skipped |
Pattern: Same as GatewayLLM and NuAuthor — the Access application sits in front of the tunnel for Cloudflare network protection, but uses a full bypass policy so the app’s own FastAPI/JWT authentication governs access. No Cloudflare login screen is shown to users.
Tunnel facts
Section titled “Tunnel facts”| Item | Value |
|---|---|
| Tunnel name | lyncareos |
| Tunnel ID | c0396e69-b202-48eb-a3c7-925b0d7c618c |
| Credentials file (VPS) | /etc/cloudflared/c0396e69-b202-48eb-a3c7-925b0d7c618c.json |
| Config file (VPS) | /etc/cloudflared/config.yml (installed from cloudflared/config.vps.yml) |
| Credentials file (workstation — source copy) | %USERPROFILE%\.cloudflared\c0396e69-b202-48eb-a3c7-925b0d7c618c.json |
| Public hostname (app) | app.lyncareos.com → http://localhost:8020 |
| App port (Docker) | 8020 |
| cloudflared host | VPS systemd service — not the workstation Windows service (stopped/disabled) |
DNS records (Cloudflare dashboard — lyncareos.com zone)
Section titled “DNS records (Cloudflare dashboard — lyncareos.com zone)”Both records must be proxied (orange cloud):
| Type | Name | Content |
|---|---|---|
| CNAME | lyncareos.com | c0396e69-b202-48eb-a3c7-925b0d7c618c.cfargotunnel.com |
| CNAME | www | c0396e69-b202-48eb-a3c7-925b0d7c618c.cfargotunnel.com |
Note: The API token in
.env.productionneedsZone → DNS → Editpermission to write these records programmatically. If it is read-only, add them via the Cloudflare dashboard manually.
Starting the production stack (VPS — live traffic)
Section titled “Starting the production stack (VPS — live traffic)”The production stack is started and managed on the VPS via the scripts in scripts/. For deploy, see 03 - DEPLOYMENT AND PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md §4. §13 below retains the detailed deploy.ps1 command reference.
Quick start (assuming stack is stopped, image already pulled):
# On VPS — /opt/lyncareosdocker compose -f docker-compose.yml -f docker-compose.vps.yml \ --env-file .env.production --profile production \ up -d --no-buildVerify: curl http://127.0.0.1:8020/api/billing/tiers — expect HTTP 200. Then https://app.lyncareos.com in a browser.
Cloudflared tunnel management on VPS (systemd)
Section titled “Cloudflared tunnel management on VPS (systemd)”The tunnel runs as a systemd service. It was registered by vps-pull-and-start.sh during initial deployment.
# Statussystemctl status cloudflared
# Start / stop / restartsystemctl start cloudflaredsystemctl stop cloudflaredsystemctl restart cloudflared
# Logs (last 30 lines)journalctl -u cloudflared --no-pager -n 30Config: /etc/cloudflared/config.yml (source: cloudflared/config.vps.yml in the repo).
To update tunnel config:
# Edit or replace /etc/cloudflared/config.yml# Then:systemctl restart cloudflaredWorkstation cloudflared Windows service — now hosts the LM Studio tunnel (2026-05-29):
The workstation’s cloudflared service was reconfigured on 2026-05-29 to run a different tunnel — lyncareos-lmstudio (b2aa7c18-847f-411c-8985-cd394124187e). It exposes https://lmstudio.lyncareos.com → http://localhost:1234 (LM Studio) so the VPS scan_worker can call the vision model.
| Field | Value |
|---|---|
| Service name | Cloudflared (Windows service, auto-start) |
| Tunnel name | lyncareos-lmstudio |
| Tunnel ID | b2aa7c18-847f-411c-8985-cd394124187e |
| DNS | lmstudio.lyncareos.com (proxied CNAME → <id>.cfargotunnel.com) |
| Ingress | lmstudio.lyncareos.com → http://localhost:1234 |
| Install script | scripts/install-lmstudio-tunnel.ps1 |
| Token storage | Windows service registry (not on disk) |
Do NOT run the workstation tunnel against the old VPS-app tunnel ID c0396e69-… — that tunnel still runs on the VPS via systemd and they would compete. The two tunnels are now intentionally separate.
If you stop the workstation service, production prescription scans will fail gracefully (structured error to the carer, all other routes unaffected). Restart with Start-Service cloudflared (admin).
10. Applying database migrations to production
Section titled “10. Applying database migrations to production”This section is written for zero-accident production use: you keep a clear record of what ran, and you never rely on luck.
Where the truth lives
Section titled “Where the truth lives”| What | Role |
|---|---|
schema_migrations table in PostgreSQL | Canonical record of which migrations have been applied. Each row is a version string matching the migration filename without .sql (e.g. V008__schedule_item_change_audit). Do not delete rows to “fix” things — that can cause the runner to re-apply SQL or leave the DB out of sync with the app. |
backend/migrations/V*.sql | Ordered source files. Anything on disk not listed in schema_migrations is pending and will run the next time migrations execute successfully. |
App startup (init_db() → migrations.runner) | On every container start, the app applies pending files in order and records them in schema_migrations. A deploy always attempts pending migrations — if V090 runs before backfill, startup fails and the health check times out. Use .\migration-audit.ps1 -Target Vps and production-migration-preflight.ps1 before deploy. |
Non-negotiables (protect production data)
Section titled “Non-negotiables (protect production data)”- Never run
docker compose down -vagainst a stack that holds real data — it removes the named volume and destroys the database. - Always run
.\db-backup.ps1 -Target Productionbefore applying a new migration or before a risky deploy. - Prefer idempotent SQL in migrations (
IF NOT EXISTS, additive changes). Destructive or data-mutating SQL needs extra review and rehearsal. - After any deploy, skim
docker compose logs app(or your host equivalent) for lines like[migrations] Applying …/Applied …so you see what ran. - Never configure a production
DATABASE_URLon a developer workstation for normal dev. The migration runner and the app will happily mutate whichever database the URL names. Use local or staging DSNs only, unless you are deliberately operating on production from the production host following the migration runbook. - Verify the DSN before every manual migration or restore: same rules as 11 — Hard rules.
Audit: repo vs database (no writes)
Section titled “Audit: repo vs database (no writes)”From the repo root (requires target flag — always use -Target Production for production):
.\migration-audit.ps1 -Target ProductionThis prints everything already recorded in schema_migrations, every V*.sql file in the repo, and highlights PENDING (file exists, not yet in DB) or ORPHAN (row in DB, file missing — investigate). Run it before and after any migration work.
Recommended workflow (strictest — manual control)
Section titled “Recommended workflow (strictest — manual control)”Use this when you want no surprises on app startup.
-
Backup -
.\db-backup.ps1 -Target Production -
Audit -
.\migration-audit.ps1 -Target Production- confirm PENDING lists exactly the new file(s) you intend to apply. -
Rehearse (optional but ideal for non-trivial SQL) — clone DB or use a throwaway database, apply the same
.sqlwithON_ERROR_STOP, fix forward.-
Option C (preferred) - use migrate.ps1 -Target Production (safe wrapper):
Terminal window .\migrate.ps1 -Target ProductionThis wrapper confirms a recent backup exists, requires explicit typed confirmation, sets DATABASE_URL to the production DSN, and runs migrations.runner. Use this unless you have a specific reason to pipe SQL manually.
-
-
Apply to production — either:
-
Option A — pipe SQL, then register the version (migration files do not insert into
schema_migrationsthemselves; the app runner does that when it applies them):Terminal window Get-Content backend\migrations\V00X__my_migration.sql | docker exec -i lyncareos-postgres-1 psql -U lyncare -d lyncareos -v ON_ERROR_STOP=1docker exec lyncareos-postgres-1 psql -U lyncare -d lyncareos -c "INSERT INTO schema_migrations (version, description) VALUES ('V00X__my_migration', 'short description') ON CONFLICT (version) DO NOTHING;"Use the exact
versionstring as the file’s basename (V00X__…). -
Option B — deploy the new app image and let
init_db()apply pending migrations and insert rows — only after backup + audit, and watch logs to confirm. If you already applied the SQL manually without inserting a row, the next startup will try to run the file again; our migrations are usually idempotent (ADD COLUMN IF NOT EXISTS, etc.), then the runner inserts the row.
-
-
Verify -
.\migration-audit.ps1 -Target Productionagain (expect PENDING: none). Optionally:Terminal window docker compose exec postgres psql -U lyncare -d lyncareos -c "SELECT version, description, applied_at FROM schema_migrations ORDER BY version;"
Rehearsal database (full clone procedure)
Section titled “Rehearsal database (full clone procedure)”# 1. Backup production first (always).\db-backup.ps1 -Target Production
# 2. Rehearse on a clone$env:PGPASSWORD = "lyncare"docker exec lyncareos-postgres-1 psql -U lyncare -d postgres -c "DROP DATABASE IF EXISTS lyncareos_migration_rehearsal;"docker exec lyncareos-postgres-1 psql -U lyncare -d postgres -c "CREATE DATABASE lyncareos_migration_rehearsal OWNER lyncare;"docker exec -e "PGPASSWORD=lyncare" lyncareos-postgres-1 pg_dump -U lyncare -d lyncareos --schema-only | docker exec -i lyncareos-postgres-1 psql -U lyncare -d lyncareos_migration_rehearsal -qdocker exec -e "PGPASSWORD=lyncare" lyncareos-postgres-1 pg_dump -U lyncare -d lyncareos --data-only | docker exec -i lyncareos-postgres-1 psql -U lyncare -d lyncareos_migration_rehearsal -q
# Apply new migration to rehearsal onlyGet-Content backend\migrations\V00X__my_migration.sql | docker exec -i lyncareos-postgres-1 psql -U lyncare -d lyncareos_migration_rehearsal -v ON_ERROR_STOP=1Check applied migrations (SQL)
Section titled “Check applied migrations (SQL)”docker compose exec postgres psql -U lyncare -d lyncareos -c "SELECT version, description, applied_at FROM schema_migrations ORDER BY version;"Keep this output (or a screenshot) with your release notes when you change schema — it is your audit trail.
11. Useful one-liners
Section titled “11. Useful one-liners”# Generate a SECRET_KEYpython -c "import secrets; print(secrets.token_hex(32))"
# Check all container healthdocker compose --profile production ps
# ── PRODUCTION database (Docker volume) ──────────────────────────────────────# Connect to PRODUCTION database (psql) — always via docker exec, NOT localhost:5432docker compose exec postgres psql -U lyncare -d lyncareos
# Backup PRODUCTION database (Docker volume → local .sql file).\db-backup.ps1 -Target Production
# Compare repo migration files vs PRODUCTION schema_migrations (read-only).\migration-audit.ps1 -Target Production
# Check which migrations have been applied to PRODUCTION (SQL only)docker compose exec postgres psql -U lyncare -d lyncareos ` -c "SELECT version, applied_at FROM schema_migrations ORDER BY version;"
# View all users in PRODUCTIONdocker compose exec postgres psql -U lyncare -d lyncareos ` -c "SELECT id, username, email, role, status, is_super_admin FROM users;"
# Tail backend logs (Docker)docker compose logs -f app
# ── DEVELOPMENT database ────────────────────────────────────────────────────# Connect to DEV: either native Postgres on localhost:5432 OR Docker Postgres on the# published host port (often 5433 — NOT the same as production unless you misconfigure).# $env:PGPASSWORD = "lyncare"# & "C:\Program Files\PostgreSQL\16\bin\psql.exe" -U lyncare -h localhost -p 5432 -d lyncareos
# Apply pending SQL migrations to a LOCAL dev database only — NEVER set DATABASE_URL to production.# cd backend# $env:DATABASE_URL = "postgresql://lyncare:lyncare@localhost:5433/lyncareos" # example: Docker Postgres on host port 5433# .\venv\Scripts\python.exe -m migrations.runner --dry # list pending — READ the implied target# .\venv\Scripts\python.exe -m migrations.runner # apply
# Run tests against the test databasecd backend$env:DATABASE_URL = $null$env:TEST_DATABASE_URL = $null.\venv\Scripts\python.exe -m pytest tests/ -v
# ── DANGER ZONE ──────────────────────────────────────────────────────────────# Hard reset DEV docker database ONLY (use docker compose without --profile production)# WARNING: NEVER run 'docker compose down -v' while the production profile is active# docker compose down -v && docker compose up -d postgres12. Production (operations host) — daily operations
Section titled “12. Production (operations host) — daily operations”Production = DigitalOcean Sydney VPS
lyncareos-prod-syd1(134.199.173.206). All operations are performed over SSH from the Windows workstation. There is no production code on the workstation — the app runs exclusively on the VPS. Topology: 03 - DEPLOYMENT AND PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md §1.
12.0 Connect to the VPS
Section titled “12.0 Connect to the VPS”# From Windows workstationssh -i "$env:USERPROFILE\.ssh\lyncareos_vps" root@134.199.173.206No password required — SSH key only. If you lose the key, use the DigitalOcean web console (Droplet → Console) as a recovery path.
Once connected, all Docker operations run from /opt/lyncareos:
cd /opt/lyncareosThe Compose invocation on the VPS is:
docker compose \ -f docker-compose.yml \ -f docker-compose.vps.yml \ --env-file .env.production \ --profile production \ <subcommand>All examples in §12–§17 assume you are already SSH’d into the VPS at /opt/lyncareos.
12.1 Topology
Section titled “12.1 Topology”- VPS:
lyncareos-prod-syd1— 2 vCPU / 4 GB, Ubuntu 24.04 LTS. - App files:
/opt/lyncareos/— compose files and.env.production. - App image:
magna123456/lyncareos:<tag>pulled from Docker Hub (no build on VPS). - Compose: uses both
docker-compose.ymlanddocker-compose.vps.ymloverride. - App URL (public):
https://app.lyncareos.comvia cloudflared systemd service →http://127.0.0.1:8020. - Data: Docker volume
lyncare_pg_data(bind-mount →/data/pg, DigitalOcean 50 GB block volumelyncareos-pg-data).
12.2 First check each session
Section titled “12.2 First check each session”# On VPS (SSH'd in, cd /opt/lyncareos)docker compose -f docker-compose.yml -f docker-compose.vps.yml \ --env-file .env.production --profile production psAll five services should be running / healthy:
lyncareos-postgres-1— healthylyncareos-pgbouncer-1— healthylyncareos-redis-1— healthylyncareos-app-1— uplyncareos-scan_worker-1— up
12.3 Tail logs
Section titled “12.3 Tail logs”docker logs -f --tail=100 lyncareos-app-112.4 Database shell
Section titled “12.4 Database shell”docker exec -it lyncareos-postgres-1 psql -U lyncare -d lyncareos12.5 Restart the app (no Postgres disruption)
Section titled “12.5 Restart the app (no Postgres disruption)”cd /opt/lyncareosdocker compose -f docker-compose.yml -f docker-compose.vps.yml \ --env-file .env.production --profile production \ restart app scan_worker12.6 Full stop → pull new image → start (emergency full-cycle)
Section titled “12.6 Full stop → pull new image → start (emergency full-cycle)”Use §13 (rolling deploy via Docker Hub) for routine deploys. Use this section only if you need to force a completely fresh container creation (e.g. compose file change, volume reconfiguration).
Non-negotiable: Never add -v to down — that deletes lyncare_pg_data and destroys the database.
| Situation | Use |
|---|---|
| Quick recycle, same image | §12.5 — restart app scan_worker |
| New app code, routine deploy | §13 — .\scripts\deploy.ps1 from workstation |
| Full stop + fresh start, same image | This section |
# On VPS — full cycle (data volumes kept)cd /opt/lyncareos
# 1. Take a backup firstdocker exec lyncareos-postgres-1 \ pg_dump -U lyncare -d lyncareos --format=custom \ -f /tmp/pre-restart-$(date +%Y%m%d%H%M).dump
# 2. Stop containers (volumes KEPT — no -v)docker compose -f docker-compose.yml -f docker-compose.vps.yml \ --env-file .env.production --profile production down
# 3. Start stack with existing pulled image (no build on VPS)docker compose -f docker-compose.yml -f docker-compose.vps.yml \ --env-file .env.production --profile production up -d --no-buildExpect a brief outage (< 30 s) while containers restart and health checks pass.
12.7 Production secrets audit (workstation, read-only)
Section titled “12.7 Production secrets audit (workstation, read-only)”Maps to A2 in 04-ROADMAP §1 Launch and §1.1 Secrets register.
Script: scripts/production-secrets-audit.ps1 — SSH to the VPS, checks that required keys exist in /opt/lyncareos/.env.production (names only, no secret values printed), confirms Stripe sk_live_ prefix, and hits GET /api/billing/tiers on localhost.
When to run
| Situation | Run? |
|---|---|
After editing .env.production on the VPS | Yes |
After deploy.ps1 or any docker compose … up -d that recreates app | Yes (confirms env loaded) |
Before rotating SECRET_KEY | Yes — expect a WARN until MFA_ENCRYPTION_KEY is pinned (D13) |
After pinning MFA_ENCRYPTION_KEY or PHI_* keys | Yes — WARN should clear for MFA |
| Routine local dev only | No |
When not to run: You do not need this on every session. A passing audit from a prior date in 04-ROADMAP does not expire unless production env changed.
From the repo root (Windows workstation):
cd D:\Projects\LynCareOS.\scripts\production-secrets-audit.ps1Requires SSH key %USERPROFILE%\.ssh\lyncareos_vps and outbound access to 134.199.173.206.
What a healthy production pass looks like
[OK]for:ENVIRONMENT,SECRET_KEY,PHI_ENCRYPTION_KEY,PHI_BLIND_INDEX_KEY,STRIPE_SECRET_KEY,STRIPE_WEBHOOK_SECRET,GOOGLE_CLIENT_ID[OK]Stripe mode: live (sk_live_prefix)[OK]GET /api/billing/tiers-> HTTP 200[WARN]MFA_ENCRYPTION_KEY not setis acceptable for day-2 ops but must be resolved beforeSECRET_KEYrotation (D13 in 32-KNOWN-DEBTS-REGISTER.md)
Exit code 0 = all required keys present. Exit code 1 = at least one required key missing or Stripe still in test mode.
Related scripts (mutate production — use only when intentional)
| Script | Purpose |
|---|---|
scripts/production-phi-pin.ps1 | Pin PHI_ENCRYPTION_KEY and PHI_BLIND_INDEX_KEY on VPS if missing after redeploy |
scripts/deploy.ps1 | Routine app image roll (doc 20) |
Pin MFA_ENCRYPTION_KEY (closes D13)
Generate on the workstation (do not commit the value):
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"Append to /opt/lyncareos/.env.production on the VPS, then recreate containers so Compose reloads env (restart alone is not enough):
# On VPScd /opt/lyncareosdocker compose -f docker-compose.yml -f docker-compose.vps.yml \ --env-file .env.production --profile production \ up -d --force-recreate app scan_workerRe-run .\scripts\production-secrets-audit.ps1 from the workstation — MFA line should show [OK].
13. App image roll — command reference (deploy is doc 20)
Section titled “13. App image roll — command reference (deploy is doc 20)”Canonical deploy guide: 03 - DEPLOYMENT AND PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md §4. This section retains the detailed command reference.
This is the canonical low-disruption deploy path for shipping new code. Postgres, Redis, and PgBouncer keep running throughout — only app and scan_worker are replaced by a new Docker Hub image.
No git is required on the VPS. The image is built on the workstation, pushed to Docker Hub, and pulled onto the VPS.
Both
appandscan_workeralways update together. They sharebackend/Dockerfile— the same image, different startup commands.
13.1 Deploy — one command
Section titled “13.1 Deploy — one command”cd D:\Projects\LynCareOS.\scripts\deploy.ps1The script handles every step in sequence:
- Pre-flight (SSH, Docker,
.env.production) npm run buildinfrontend/(unless-SkipBuild)production-migration-preflight.ps1 -RunBackfillIfNeeded— VPSenc_versioncheck; runs PHI backfill before V090 if needed- Pre-deploy
pg_dumpon VPS - Docker build + push to Hub
- VPS pull + restart
app/scan_worker - Smoke test (up to 120 s — large migration batches on startup)
production-phi-pin.ps1— append HKDF-derivedPHI_*keys to VPS.envwhen missing
It stops immediately if a step fails. If step 7 fails after a migration error, see §13.2 and 11-DATABASE-SAFETY-AND-MIGRATIONS.md §7.
Optional flags:
.\scripts\deploy.ps1 -Tag v1.2.3 # give the release a meaningful name.\scripts\deploy.ps1 -SkipBuild # push existing :latest without rebuildingHelper scripts:
| Script | Purpose |
|---|---|
.\migration-audit.ps1 -Target Vps -NonInteractive | Repo vs VPS schema_migrations (read-only) |
.\scripts\production-migration-preflight.ps1 | enc_version counts; optional backfill |
.\scripts\production-phi-pin.ps1 | Pin PHI_ENCRYPTION_KEY / PHI_BLIND_INDEX_KEY on VPS |
.\scripts\dev-phi-pin.ps1 | Pin same keys in backend/.env (dev / lyncareos_dev) |
13.2 Watch for migrations
Section titled “13.2 Watch for migrations”init_db() applies pending migrations on every app startup (not a separate operator step):
ssh -i "$env:USERPROFILE\.ssh\lyncareos_vps" root@134.199.173.206 ` "docker logs lyncareos-app-1 2>&1 | grep -i migrat"Look for [migrations] Applying … / Applied …. If none appear, all migrations were already applied.
V090 failure (email_enc NOT NULL): Backfill was skipped. Run .\scripts\production-migration-preflight.ps1 -RunBackfillIfNeeded, then restart app (doc 11 §5). Do not roll back the image until you understand which migrations recorded in schema_migrations.
Scheduler fix (2026-05-22): Background jobs (alert_scheduler, scheduler) must use await conn.set_autocommit(...) — not conn.autocommit = … on async psycopg connections.
13.3 Rollback
Section titled “13.3 Rollback”Application image rollback
Section titled “Application image rollback”Pass the previous tag with -SkipBuild (no rebuild needed — the old image is still on Docker Hub):
.\scripts\deploy.ps1 -SkipBuild -Tag deploy-20260519-1100Find previous tag names in Docker Hub: https://hub.docker.com/r/magna123456/lyncareos/tags
The script will:
- Push the old tag to Docker Hub (it’s already there, so the push is instant)
- Update
APP_IMAGEon the VPS to the old tag - Pull and recreate containers (
--redeployskips pg_restore) - Run the smoke test to confirm HTTP 200
Migration rollback (failed V### migration on startup)
Section titled “Migration rollback (failed V### migration on startup)”The migration runner commits each migration in its own transaction. If migration Vnnn fails, the runner raises and the application exits — it will not boot with a partially applied schema.
Procedure when a migration causes a boot failure:
- Roll back the app image to the previous tag (see above) — the old code works with the old schema.
- On the VPS, inspect the broken migration:
docker logs --tail=80 lyncareos-app-1 2>&1 | grep -i migrat- Connect to the database and manually check the migration table:
docker exec -it lyncareos-postgres-1 psql -U lyncare -d lyncareos \ -c "SELECT version, applied_at FROM schema_migrations ORDER BY version DESC LIMIT 5;"- If the migration was partially applied, manually undo the DDL (drop the column / index) and remove the row from
schema_migrations— or restore from the pre-deploy backup at/tmp/pre-deploy-<tag>.dump:
# Restore from pre-deploy backup (only if data must be recovered — this overwrites the DB)docker exec -i lyncareos-postgres-1 \ pg_restore -U lyncare -d lyncareos --clean --if-exists < /tmp/pre-deploy-<tag>.dump- Fix the migration SQL, re-build and re-deploy with a new tag.
Rule: Never delete rows from
schema_migrationsunless you are simultaneously undoing the DDL that migration applied. The two must remain in sync.
14. Production (operations host) — Cloudflare Tunnel management
Section titled “14. Production (operations host) — Cloudflare Tunnel management”cloudflared runs as a systemd service on the VPS (not inside the Compose stack and not on the workstation — the workstation Cloudflared service is stopped and disabled).
| Item | Value |
|---|---|
| Tunnel ID | c0396e69-b202-48eb-a3c7-925b0d7c618c |
| Config file | /etc/cloudflared/config.yml (installed from cloudflared/config.vps.yml) |
| Credentials | /etc/cloudflared/c0396e69-b202-48eb-a3c7-925b0d7c618c.json |
| Ingress | app.lyncareos.com → http://localhost:8020 |
| DNS | app CNAME c0396e69-….cfargotunnel.com (already configured — no change needed) |
Check tunnel status (on VPS):
systemctl status cloudflared --no-pager -n 10Restart after config change (on VPS):
systemctl restart cloudflaredsleep 3systemctl is-active cloudflared # expect: activeIf the public URL fails but http://127.0.0.1:8020 works: the problem is the tunnel or DNS, not the app container. Check journalctl -u cloudflared --no-pager -n 30.
Workstation cloudflared (Cloudflared Windows service): Running since 2026-05-29 — hosts the LM Studio tunnel (lyncareos-lmstudio / b2aa7c18-…) which routes https://lmstudio.lyncareos.com → http://localhost:1234 for production prescription scans. This is a different tunnel to the VPS app tunnel (c0396e69-…); they do not compete. See §9 above for full detail.
15. Production (operations host) — backups and restore drill
Section titled “15. Production (operations host) — backups and restore drill”Canonical procedure (dev-first, fail-safes, migration gate): 23-BACKUP-RESTORE-DRILL.md. Run
.\scripts\backup-restore-drill-dev.ps1on the workstation before the VPS A5 checklist below.
15.1 Production backup — VPS + workstation (automated)
Section titled “15.1 Production backup — VPS + workstation (automated)”Canonical script: .\scripts\vps-production-backup.ps1 — tier 1 required on VPS; tier 2 best-effort copy to backups\ when this PC is online. Workstation unreachable is not a deploy or backup failure; the next run retries.
# Fresh pg_dump on VPS + pull to backups\.\scripts\vps-production-backup.ps1
# Wrapper (same behaviour).\scripts\pull-vps-backup-to-workstation.ps1Log: backups/backup-run-log.jsonl. Full dump: pg_dump -Fc of entire lyncareos. Retention: 10 on VPS /tmp/ + 10 production copies on this PC (see 23 promotion pipeline).
deploy.ps1: pre-deploy dump on VPS; post-deploy calls vps-production-backup.ps1 -RemoteDumpPath (best-effort tier 2).
Schedule: weekly Task Scheduler on this PC when powered on — see 23-BACKUP-RESTORE-DRILL.md.
Manual ad-hoc on VPS (if SSH only):
TS=lyncareos_$(date +%Y%m%d_%H%M%S).dumpdocker exec lyncareos-postgres-1 pg_dump -U lyncare -d lyncareos --format=custom > /tmp/$TSls -lh /tmp/$TS15.2 Cloud offsite (tier 3 — B2) — deferred at current scale
Section titled “15.2 Cloud offsite (tier 3 — B2) — deferred at current scale”Workstation copy (tier 2) is the offsite copy for now (not on DigitalOcean). Backblaze B2 + rclone remains P2 until traffic warrants geo-redundant cloud — 99-ARCHIVE/25-PRODUCTION-SERVER-BUILD-AND-PROVIDER-ANALYSIS.md.
| When | Action |
|---|---|
Each deploy.ps1 | Pre-deploy VPS dump + post-deploy workstation pull (built in) |
| Weekly (this PC) | vps-production-backup.ps1 |
| At scale | VPS cron + rclone → B2 (roadmap A8) |
15.3 Restore drill (on VPS) — Phase A5
Section titled “15.3 Restore drill (on VPS) — Phase A5”Status (2026-06-02): A5 + Phase 3 destructive restore complete — side-DB drill + full overwrite of live lyncareos rehearsed (backup-restore-drill-vps-production.ps1); 9 users / 4 tenants preserved; /api/billing/tiers 200 on VPS after restart. Log: backups/drill-log.jsonl. Automate: backup-restore-drill-dev.ps1 → backup-restore-drill-vps.ps1 → (optional disaster rehearsal) backup-restore-drill-vps-production.ps1 -IUnderstand. Maps to 04-ROADMAP §1 Launch (A5) and 23-BACKUP-RESTORE-DRILL.md.
Goal: Prove you can recover Postgres from a pg_dump / pg_restore without guessing during an incident.
Prerequisites
- Phase 1 dev drill passed —
.\scripts\backup-restore-drill-dev.ps1(see doc 23). - Migrations in sync —
.\migration-audit.ps1 -Target Devand-Target Vps -NonInteractiveshow PENDING: none. - SSH to
lyncareos-prod-syd1(root@134.199.173.206, key~/.ssh/lyncareos_vps). - App traffic can stay up; the drill uses a separate test database (
lyncareos_restore_test). - Maintenance window not required for the test-restore path below.
Checklist (record results in your ops log)
| Step | Action | Pass? |
|---|---|---|
| 1 | Take a fresh custom-format dump (§15.1) — note filename and size | |
| 2 | Create lyncareos_restore_test | |
| 3 | pg_restore dump into test DB | |
| 4 | Compare users / tenants counts: production vs test | |
| 5 | Spot-check one known tenant or user exists in test DB | |
| 6 | Drop lyncareos_restore_test (cleanup) | |
| 7 | Optional: copy dump off-box via scp to backups\ on workstation |
Commands — test restore (non-destructive)
# On VPS — set TS to the dump you just created (custom format)TS=lyncareos_YYYYMMDD_HHMM # example — use your actual filename stem
docker exec lyncareos-postgres-1 \ psql -U lyncare -d postgres -c "DROP DATABASE IF EXISTS lyncareos_restore_test;"docker exec lyncareos-postgres-1 \ psql -U lyncare -d postgres -c "CREATE DATABASE lyncareos_restore_test OWNER lyncare;"
docker exec lyncareos-postgres-1 \ pg_restore --no-owner -U lyncare -d lyncareos_restore_test /tmp/${TS}.dump
# Verify row counts match productiondocker exec lyncareos-postgres-1 \ psql -U lyncare -d lyncareos -c "SELECT 'prod' AS db, COUNT(*) AS users FROM users; SELECT COUNT(*) AS tenants FROM tenants;"
docker exec lyncareos-postgres-1 \ psql -U lyncare -d lyncareos_restore_test \ -c "SELECT 'test' AS db, COUNT(*) AS users FROM users; SELECT COUNT(*) AS tenants FROM tenants;"
# Cleanup test databasedocker exec lyncareos-postgres-1 \ psql -U lyncare -d postgres -c "DROP DATABASE lyncareos_restore_test;"Workstation backup (read-only dump) — when SSH’d to the machine that runs Docker production locally, or after downloading a VPS dump:
# From repo root on the operations host — does NOT replace the VPS drill above.\db-backup.ps1 -Target ProductionA5 roadmap status: Complete 2026-06-02 — recorded in 04-ROADMAP §1 and backups/drill-log.jsonl.
If the restore test passes and you need to restore production (e.g. after data loss):
# DESTRUCTIVE — production data is overwrittendocker compose -f /opt/lyncareos/docker-compose.yml \ -f /opt/lyncareos/docker-compose.vps.yml \ --env-file /opt/lyncareos/.env.production --profile production \ stop app scan_worker
docker exec lyncareos-postgres-1 \ psql -U lyncare -d postgres -c "DROP DATABASE lyncareos;"docker exec lyncareos-postgres-1 \ psql -U lyncare -d postgres -c "CREATE DATABASE lyncareos OWNER lyncare;"
# Dump path is inside the postgres container (pg_dump -f /tmp/….dump)docker exec lyncareos-postgres-1 \ pg_restore --no-owner -U lyncare -d lyncareos /tmp/lyncareos_<timestamp>.dump
# Workstation automation: .\scripts\backup-restore-drill-vps-production.ps1 -IUnderstand
# Restart appdocker compose -f /opt/lyncareos/docker-compose.yml \ -f /opt/lyncareos/docker-compose.vps.yml \ --env-file /opt/lyncareos/.env.production --profile production \ up -d --no-build app scan_worker16. Production (operations host) — incident response
Section titled “16. Production (operations host) — incident response”16.1 External 502/504, app looks healthy locally
Section titled “16.1 External 502/504, app looks healthy locally”- SSH into VPS:
ssh -i "$env:USERPROFILE\.ssh\lyncareos_vps" root@134.199.173.206 - Check app responds locally:
curl -s -o /dev/null -w "HTTP %{http_code}\n" http://127.0.0.1:8020/api/billing/tiers - If 200: check cloudflared —
systemctl status cloudflared; restart if needed. - If not 200: check app logs —
docker logs --tail=60 lyncareos-app-1 - Cloudflare DNS: confirm
appCNAME still points toc0396e69-….cfargotunnel.com.
16.2 App crash-loop
Section titled “16.2 App crash-loop”docker logs --tail=100 lyncareos-app-1— look for the error on startup.- Common causes: bad env var (SECRET_KEY, DATABASE_URL, Stripe key), Postgres unavailable, migration failure.
- Compare env vars against 04-ROADMAP §1.1 Secrets register.
- Restart after fixing:
docker compose -f docker-compose.yml -f docker-compose.vps.yml --env-file .env.production --profile production restart app
16.3 Disk full — OS disk
Section titled “16.3 Disk full — OS disk”df -h /docker system prune --volumes # removes stopped containers, unused images, build cacheNever run
docker volume prune— it would deletelyncare_pg_data.
16.4 Disk full — block volume (/data/pg)
Section titled “16.4 Disk full — block volume (/data/pg)”df -h /data/pgResize the DigitalOcean volume in the control panel (no downtime for ext4 online resize), then:
resize2fs /dev/sda # (or whatever device /data/pg is mounted on — check with `lsblk`)16.5 Cannot SSH (key lost or locked out)
Section titled “16.5 Cannot SSH (key lost or locked out)”Use the DigitalOcean web console: Droplet → Access → Launch Droplet Console. You can add a new SSH public key there without needing the existing one.
16.6 VPS needs to be rebuilt (data loss scenario)
Section titled “16.6 VPS needs to be rebuilt (data loss scenario)”- Provision a new DigitalOcean droplet in Sydney.
- Attach the same 50 GB block volume (
lyncareos-pg-data) — data survives a Droplet rebuild. - Run
vps-bootstrap-syd1.shon the new Droplet. - Copy
.env.production, compose files, and tunnel credentials from workstation. - Run
vps-pull-and-start.sh(skips pg_restore if DB volume intact; uses--redeploy). - Verify
https://app.lyncareos.comresponds.
17. Production (operations host) — common one-liners
Section titled “17. Production (operations host) — common one-liners”All commands below are run on the VPS after SSH:
# Connect from workstationssh -i "$env:USERPROFILE\.ssh\lyncareos_vps" root@134.199.173.206# ── Status ────────────────────────────────────────────────────────────────────docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
# ── Logs ──────────────────────────────────────────────────────────────────────docker logs -f --tail=50 lyncareos-app-1
# ── Database shell ────────────────────────────────────────────────────────────docker exec -it lyncareos-postgres-1 psql -U lyncare -d lyncareos
# ── Applied migrations ────────────────────────────────────────────────────────docker exec lyncareos-postgres-1 \ psql -U lyncare -d lyncareos \ -c "SELECT version, applied_at FROM schema_migrations ORDER BY version DESC LIMIT 10;"
# ── Smoke test ────────────────────────────────────────────────────────────────curl -s -o /dev/null -w "HTTP %{http_code}\n" http://127.0.0.1:8020/api/billing/tiers
# ── cloudflared ───────────────────────────────────────────────────────────────systemctl status cloudflared --no-pager -n 5systemctl restart cloudflared
# ── Backup ────────────────────────────────────────────────────────────────────docker exec lyncareos-postgres-1 \ pg_dump -U lyncare -d lyncareos --format=custom \ -f /tmp/lyncareos_$(date +%Y%m%d%H%M).dump
# ── Disk ──────────────────────────────────────────────────────────────────────df -h / /data/pgdocker system dfRoutine rolling deploy — from workstation (see §13):
# 1. Build and push new image$tag = "build-$(Get-Date -Format 'yyyyMMdd')".\scripts\build-and-push.ps1 -HubUser magna123456 -Tag $tag
# 2. Backupssh -i "$env:USERPROFILE\.ssh\lyncareos_vps" root@134.199.173.206 ` "docker exec lyncareos-postgres-1 pg_dump -U lyncare -d lyncareos --format=custom -f /tmp/pre-deploy-\$(date +%Y%m%d%H%M).dump && echo OK"
# 3. Ship files.\scripts\vps-scp-deploy-files.ps1 -HubUser magna123456 -Tag $tag
# 4. Pull + restartssh -i "$env:USERPROFILE\.ssh\lyncareos_vps" root@134.199.173.206 ` "bash /opt/lyncareos/scripts/vps-pull-and-start.sh --redeploy"
# 5. VerifyInvoke-WebRequest -Uri "https://app.lyncareos.com/api/billing/tiers" -UseBasicParsing | Select-Object StatusCode18. PostgreSQL collation — REINDEX after VPS OS upgrade
Section titled “18. PostgreSQL collation — REINDEX after VPS OS upgrade”LynCareOS databases use glibc-backed collation (en_US.utf8 in dev and Docker UAT; production matches the Postgres image on the VPS). Storage of UTF-8 text is unaffected by a host OS upgrade, but sort order and text indexes depend on the host’s glibc collation version. Upgrading the VPS operating system (routine apt upgrade, kernel/glibc updates, or rebuilding the Droplet on a newer base image) can leave indexes inconsistent until PostgreSQL is told to rebuild them.
This is standard operations — not optional i18n work. Non-ASCII patient or carer names make wrong sort order visible; i18n increases the volume of non-ASCII data over time.
When to run (triggers)
Section titled “When to run (triggers)”| Event | REINDEX required? |
|---|---|
deploy.ps1 / app image roll only (containers updated, host OS unchanged) | No |
VPS OS or glibc upgrade on lyncareos-prod-syd1 | Yes — mandatory before closing the change |
Workstation OS upgrade affecting Docker Postgres used for --profile production rehearsal | Yes on that Docker database when non-ASCII sort is used in tests |
| Native dev Postgres on Windows after major OS upgrade | Recommended if you rely on ORDER BY on non-ASCII columns in dev |
Control
Section titled “Control”- Treat REINDEX as a gate on the post–OS-upgrade checklist (same severity as “containers healthy” and API smoke).
- Record date, operator, and command output (success line from
psql) in the change note, incident ticket, or deploy log. - If the upgrade coincides with a release, run full backup first — same rule as deploy (doc 23); use
.\scripts\vps-production-backup.ps1when no recent dump exists.
Canonical database context: 11-DATABASE-SAFETY-AND-MIGRATIONS.md §2q.
Procedure — production (on VPS after SSH)
Section titled “Procedure — production (on VPS after SSH)”# 1. Confirm Postgres is updocker ps --filter name=lyncareos-postgres-1 --format "{{.Names}} {{.Status}}"
# 2. Rebuild all indexes in the live database (blocks writes briefly — run in a maintenance window)docker exec lyncareos-postgres-1 \ psql -U lyncare -d lyncareos -v ON_ERROR_STOP=1 \ -c "REINDEX DATABASE lyncareos;"
# 3. Optional: confirm no invalid indexes (should return zero rows)docker exec lyncareos-postgres-1 \ psql -U lyncare -d lyncareos -c \ "SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;"Workstation verification after production REINDEX:
curl.exe -s -o NUL -w "%{http_code}" https://app.lyncareos.com/api/billing/tiersSpot-check any screen that sorts people or lists by name when non-ASCII data exists.
Procedure — Docker UAT (local rehearsal DB)
Section titled “Procedure — Docker UAT (local rehearsal DB)”From repo root, with the production profile stack running:
docker exec lyncareos-postgres-1 psql -U lyncare -d lyncareos -v ON_ERROR_STOP=1 -c "REINDEX DATABASE lyncareos;"Related
Section titled “Related”- Deploy guide — day-2: 20-PRODUCTION-DEPLOYMENT-GUIDE.md §7
- i18n design (why this matters): docs/plans/2026-08-03-i18n-p0-p1-design.md §3.7