Skip to content

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.


  1. Architecture overview
  2. Prerequisites
  3. Development — Startup
  4. Development — Shutdown
  5. Troubleshooting dev environment
  6. Building Docker images
  7. Running full-stack in Docker
  8. Production environment variables
  9. Cloudflare Tunnel — connectivity reference
  10. Database migrations (safe workflow)
  11. Useful one-liners
  12. Production (operations host) — daily operations
  13. App image roll — command reference (deploy is doc 20)
  14. Production (operations host) — Cloudflare Tunnel management
  15. Production (operations host) — backups & restore drill
  16. Production (operations host) — incident response
  17. Production (operations host) — common one-liners
  18. PostgreSQL collation — REINDEX after VPS OS upgrade

⚠️ 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)
InstanceNative Windows postgres.exe (or your dev DB on 5432)Docker lyncareos-postgres-1
Data volumeNative install / lyncareos_devDocker named volume lyncare_pg_data
How to connectpsql -U lyncare -h localhost -p 5432docker exec … psql … or GUI to 127.0.0.1:5433 (default published port)
BackendLocal FastAPI on 8021 (§3)app container (Compose production profile) on localhost:8020 (§7)
RoleDay-to-day work and integration-style testing before production; this is the stand-in for a separate UAT tierUse when you need a built SPA + same image shape as production; not required for routine validation

Rule: Never use docker compose down -v when the lyncare_pg_data volume has data you care about (optional Docker DB) — -v deletes the volume. For disposable resets, -v is fine.

Rule: From Windows, localhost:5432 usually hits native dev Postgres, not the Docker container (Docker is typically on 5433). Verify host/port before running DDL.

Production (operations host)Non-production (not a second “UAT server”)
URLhttps://app.lyncareos.com via Cloudflare Tunnel → localhost:8020 on that hostDefault: Vite + API — http://localhost:5173 → 8021 (dev / proxy UAT). Optional: http://localhost:8020 if you started full-stack Docker (§7).
Operator accessPowerShell 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/.env on a machine used for Vite / npm run dev or 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.runner or manual DDL against a DSN you have not explicitly verified (host, port, database name). A typo or a copied-from-prod .env can apply migrations to the wrong cluster.
  • Prefer separate files for production-only secrets (e.g. backend/.env.production only on the server, gitignored) and keep dev DATABASE_URL pointed at local or explicitly non-production databases (Docker Postgres on localhost with 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 valueBackendDatabase
http://localhost:8021Local FastAPI (dev)lyncareos_dev (port 5432) — correct for dev and proxy-UAT work
http://localhost:8020Docker 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:

Terminal window
Get-Content frontend\.env | Select-String VITE_API_URL
# Must show: VITE_API_URL=http://localhost:8021

Restart 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.


ToolMin versionCheck
Docker Desktop4.xdocker --version
Docker Composev2 (bundled with Docker Desktop)docker compose version
Python3.12python --version
Node.js20+node --version
npm9+npm --version

Python venv must be created once before first use:

Terminal window
cd backend
python -m venv venv
venv\Scripts\pip install -r requirements.txt

Node modules must be installed once:

Terminal window
cd frontend
npm install

Run the startup script from the project root:

Terminal window
.\dev-start.ps1

This does all three steps below in sequence and waits for each service to be healthy before proceeding.


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.

Terminal window
# Confirm the native Windows PG service is running
Get-Service -Name postgresql*
# Test connectivity (expects "1" as output)
psql -h localhost -p 5432 -U lyncare -d postgres -c "SELECT 1" -tA

If the service is stopped, start it via Windows Services (services.msc) or:

Terminal window
Start-Service postgresql*

Ensure lyncareos_dev database exists (only needed once):

Terminal window
psql -h localhost -p 5432 -U lyncare -d postgres -c "CREATE DATABASE lyncareos_dev OWNER lyncare;" 2>$null

Do not run docker compose up -d postgres for dev. That starts the production Docker postgres container.

Windows requirement: uvicorn must use --loop asyncio on Windows. The --loop asyncio flag forces SelectorEventLoop, which psycopg requires. Without it, psycopg raises Psycopg cannot use the 'ProactorEventLoop' and the server starts but cannot execute any database queries.

Critical: always clear DATABASE_URL from the shell session before starting the server. Test runs set DATABASE_URL=…_test in 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.ps1 multiple 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.

Terminal window
# 0. Kill any stale backend processes on port 8021
$stalePids = (netstat -ano | Select-String ":8021 .*LISTENING") |
ForEach-Object { ($_ -split '\s+')[-1] } | Sort-Object -Unique
if ($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 `
--reload

Expected 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”
Terminal window
cd frontend
npm run dev

Expected output:

VITE ready in xxx ms
➜ Local: http://localhost:5173/

The browser tab opens at http://localhost:5173.


ServiceURL
Frontend (React)http://localhost:5173
Backend APIhttp://localhost:8021
Swagger / API docshttp://localhost:8021/api/docs
PostgreSQL (dev)Native Windows PostgreSQL localhost:5432, database lyncareos_dev
ItemValue
App login usernamePeter
App login passwordSee 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:5432 from Windows reaches native Windows PostgreSQL when installed — not the Docker Postgres container. Compose publishes Docker Postgres on a different host port (default 5433). backend/.env → DATABASE_URL must 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 production DATABASE_URL into a dev machine. See Architecture overview.


Terminal window
.\dev-stop.ps1
Terminal window
# 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):
```powershell
docker compose down -v

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.

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):

Terminal window
Get-Content frontend\.env | Select-String VITE_API_URL

If 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:

Terminal window
# 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:

Terminal window
netstat -ano | findstr ":8021 " | findstr LISTENING
# More than one PID = stale processes present
Get-Process | Where-Object { $_.Name -match "python" } |
Select-Object Id, StartTime, CommandLine | Format-List

Fix — kill everything on the port, then start fresh:

Terminal window
$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)

The Vite proxy forwards /api/* to the backend. A 502 means the backend is not running.

Terminal window
# Confirm port 8021 is not listening
netstat -ano | Select-String ":8021.*LISTENING"
# Restart backend (Steps 2 above)

Almost always caused by DATABASE_URL pointing to the test database.

Terminal window
# 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 uvicorn

401 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):

Terminal window
cd backend
python seed_admin.py # updates by ADMIN_EMAIL or ADMIN_USERNAME; refreshes email_enc + email_idx

Fix (all decryptable users):

Terminal window
cd backend
python -m migrations.scripts.repair_phi_email_indexes

Legacy 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):

Terminal window
cd backend
python tools/diagnose_login_phi.py
# Release gate (counts only) — also used by push-to-production / deploy:
# .\scripts\verify-phi-crypto-health.ps1 -Target DockerUat|Vps

See 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.

Check the backend log for a startup error. Most common cause is DATABASE_URL not set or PostgreSQL not running.

Terminal window
# Is Postgres running?
docker compose ps
# If not:
docker compose up -d postgres

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.


The Dockerfile lives at backend/Dockerfile. It is a two-stage build:

  • Stage 1 (build-frontend): Node 22, runs npm ci && npm run build, produces frontend/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.

Run from the project root (where .dockerignore lives):

Terminal window
docker build \
-f backend/Dockerfile \
-t lyncareos:latest \
.

Tag for a specific release:

Terminal window
docker build -f backend/Dockerfile -t lyncareos:1.0.0 .
Terminal window
# Check image size
docker images lyncareos
# Start a shell in the image for inspection
docker run --rm -it lyncareos:latest /bin/bash

Replace <registry> with your registry host (e.g. Docker Hub, AWS ECR, Cloudflare, GitHub Container Registry):

Terminal window
docker tag lyncareos:latest <registry>/lyncareos:latest
docker push <registry>/lyncareos:latest

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.

Terminal window
cp backend/.env backend/.env.production

Edit backend/.env.production — set at minimum:

ENVIRONMENT=production
SECRET_KEY=<64-char random hex> # python -c "import secrets; print(secrets.token_hex(32))"
ALLOWED_ORIGINS=https://yourdomain.com
POSTGRES_USER=lyncare
POSTGRES_PASSWORD=<strong-password>
POSTGRES_DB=lyncareos

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.

Terminal window
# Start postgres + app (uses backend/.env for secrets)
docker compose --profile production up -d

For a dedicated production env file instead:

Terminal window
docker compose --env-file backend/.env.production --profile production up -d

Ensure that file defines SECRET_KEY and ALLOWED_ORIGINS (and matches your DB credentials if you override Postgres).

Services started:

ServiceContainer portHost port (default)
postgres54325433 (POSTGRES_HOST_PORT, maps to container 5432)
app80208020

Open http://localhost:8020 — the React app is served directly by FastAPI.

Terminal window
docker compose logs -f app
docker compose logs -f postgres
Terminal window
docker compose --profile production down
# Add -v to also delete the database volume (DESTRUCTIVE)
Terminal window
# Rebuild image with latest code
docker 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 app

Stop 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).

  1. Stop the stack (containers removed; named volume lyncare_pg_data is kept):

    Terminal window
    docker compose --profile production down

    If you use a production env file for secrets:

    Terminal window
    docker compose --env-file backend/.env.production --profile production down
  2. Rebuild only the application image (frontend build + Python stage):

    Terminal window
    docker compose --profile production build app
  3. Start again (Postgres comes back with the same data; app uses the new image):

    Terminal window
    docker compose --profile production up -d

    Or 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.


All configuration is injected at runtime via environment variables. The backend/.env file is never baked into the Docker image (it is in .dockerignore).

VariableRequiredDescription
ENVIRONMENTyesSet to production. Enables strict checks for missing vars.
SECRET_KEYyes64-char hex string. Sign JWT tokens. Never reuse between environments.
DATABASE_URLyesPostgreSQL DSN: postgresql://user:pass@host:port/db — this is the sole DB selector; wrong host = wrong data (see §1)
ALLOWED_ORIGINSyesComma-separated list of allowed CORS origins, e.g. https://app.lyncareos.com
POSTGRES_USERcompose onlyDB username (used by Compose to create the DB).
POSTGRES_PASSWORDcompose onlyDB password.
POSTGRES_DBcompose onlyDB name.
ACCESS_TOKEN_EXPIRE_HOURSnoDefault: 8
REFRESH_TOKEN_EXPIRE_DAYSnoDefault: 30
GOOGLE_CLIENT_IDnoEnables Google OAuth login if set.
DB_POOL_MINnoMinimum pool connections. Default: 2
DB_POOL_MAXnoMaximum pool connections. Default: 10

Generate a strong SECRET_KEY:

Terminal window
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”
ItemValue
App nameLynCareOS
App IDa3b5a0f0-89a3-48d8-a145-849dc357a899
AUD token31ac261f16409f2a6eb58bc1e514a9e716240b445b418265b16193f11b0ed7d1
Domainslyncareos.com/*, www.lyncareos.com/*
PolicyBypass — everyone (app handles its own JWT auth)
Session168h
InterstitialSkipped

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.


ItemValue
Tunnel namelyncareos
Tunnel IDc0396e69-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 hostVPS 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):

TypeNameContent
CNAMElyncareos.comc0396e69-b202-48eb-a3c7-925b0d7c618c.cfargotunnel.com
CNAMEwwwc0396e69-b202-48eb-a3c7-925b0d7c618c.cfargotunnel.com

Note: The API token in .env.production needs Zone → DNS → Edit permission 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):

Terminal window
# On VPS — /opt/lyncareos
docker compose -f docker-compose.yml -f docker-compose.vps.yml \
--env-file .env.production --profile production \
up -d --no-build

Verify: 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.

Terminal window
# Status
systemctl status cloudflared
# Start / stop / restart
systemctl start cloudflared
systemctl stop cloudflared
systemctl restart cloudflared
# Logs (last 30 lines)
journalctl -u cloudflared --no-pager -n 30

Config: /etc/cloudflared/config.yml (source: cloudflared/config.vps.yml in the repo).

To update tunnel config:

Terminal window
# Edit or replace /etc/cloudflared/config.yml
# Then:
systemctl restart cloudflared

Workstation 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.

FieldValue
Service nameCloudflared (Windows service, auto-start)
Tunnel namelyncareos-lmstudio
Tunnel IDb2aa7c18-847f-411c-8985-cd394124187e
DNSlmstudio.lyncareos.com (proxied CNAME → <id>.cfargotunnel.com)
Ingresslmstudio.lyncareos.com → http://localhost:1234
Install scriptscripts/install-lmstudio-tunnel.ps1
Token storageWindows 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.

WhatRole
schema_migrations table in PostgreSQLCanonical 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*.sqlOrdered 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.
  1. Never run docker compose down -v against a stack that holds real data — it removes the named volume and destroys the database.
  2. Always run .\db-backup.ps1 -Target Production before applying a new migration or before a risky deploy.
  3. Prefer idempotent SQL in migrations (IF NOT EXISTS, additive changes). Destructive or data-mutating SQL needs extra review and rehearsal.
  4. After any deploy, skim docker compose logs app (or your host equivalent) for lines like [migrations] Applying … / Applied … so you see what ran.
  5. Never configure a production DATABASE_URL on 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.
  6. Verify the DSN before every manual migration or restore: same rules as 11 — Hard rules.

From the repo root (requires target flag — always use -Target Production for production):

Terminal window
.\migration-audit.ps1 -Target Production

This 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.

Section titled “Recommended workflow (strictest — manual control)”

Use this when you want no surprises on app startup.

  1. Backup - .\db-backup.ps1 -Target Production

  2. Audit - .\migration-audit.ps1 -Target Production - confirm PENDING lists exactly the new file(s) you intend to apply.

  3. Rehearse (optional but ideal for non-trivial SQL) — clone DB or use a throwaway database, apply the same .sql with ON_ERROR_STOP, fix forward.

    • Option C (preferred) - use migrate.ps1 -Target Production (safe wrapper):

      Terminal window
      .\migrate.ps1 -Target Production

      This 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.

  4. Apply to production — either:

    • Option A — pipe SQL, then register the version (migration files do not insert into schema_migrations themselves; 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=1
      docker 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 version string 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.

  5. Verify - .\migration-audit.ps1 -Target Production again (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;"
Terminal window
# 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 -q
docker 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 only
Get-Content backend\migrations\V00X__my_migration.sql | docker exec -i lyncareos-postgres-1 psql -U lyncare -d lyncareos_migration_rehearsal -v ON_ERROR_STOP=1
Terminal window
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.


Terminal window
# Generate a SECRET_KEY
python -c "import secrets; print(secrets.token_hex(32))"
# Check all container health
docker compose --profile production ps
# ── PRODUCTION database (Docker volume) ──────────────────────────────────────
# Connect to PRODUCTION database (psql) — always via docker exec, NOT localhost:5432
docker 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 PRODUCTION
docker 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 database
cd 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 postgres

12. 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.

Terminal window
# From Windows workstation
ssh -i "$env:USERPROFILE\.ssh\lyncareos_vps" root@134.199.173.206

No 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:

Terminal window
cd /opt/lyncareos

The Compose invocation on the VPS is:

Terminal window
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.

  • 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.yml and docker-compose.vps.yml override.
  • App URL (public): https://app.lyncareos.com via cloudflared systemd service → http://127.0.0.1:8020.
  • Data: Docker volume lyncare_pg_data (bind-mount → /data/pg, DigitalOcean 50 GB block volume lyncareos-pg-data).
Terminal window
# 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 ps

All five services should be running / healthy:

  • lyncareos-postgres-1 — healthy
  • lyncareos-pgbouncer-1 — healthy
  • lyncareos-redis-1 — healthy
  • lyncareos-app-1 — up
  • lyncareos-scan_worker-1 — up
Terminal window
docker logs -f --tail=100 lyncareos-app-1
Terminal window
docker exec -it lyncareos-postgres-1 psql -U lyncare -d lyncareos

12.5 Restart the app (no Postgres disruption)

Section titled “12.5 Restart the app (no Postgres disruption)”
Terminal window
cd /opt/lyncareos
docker compose -f docker-compose.yml -f docker-compose.vps.yml \
--env-file .env.production --profile production \
restart app scan_worker

12.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.

SituationUse
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 imageThis section
Terminal window
# On VPS — full cycle (data volumes kept)
cd /opt/lyncareos
# 1. Take a backup first
docker 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-build

Expect 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

SituationRun?
After editing .env.production on the VPSYes
After deploy.ps1 or any docker compose … up -d that recreates appYes (confirms env loaded)
Before rotating SECRET_KEYYes — expect a WARN until MFA_ENCRYPTION_KEY is pinned (D13)
After pinning MFA_ENCRYPTION_KEY or PHI_* keysYes — WARN should clear for MFA
Routine local dev onlyNo

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):

Terminal window
cd D:\Projects\LynCareOS
.\scripts\production-secrets-audit.ps1

Requires 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 set is acceptable for day-2 ops but must be resolved before SECRET_KEY rotation (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)

ScriptPurpose
scripts/production-phi-pin.ps1Pin PHI_ENCRYPTION_KEY and PHI_BLIND_INDEX_KEY on VPS if missing after redeploy
scripts/deploy.ps1Routine app image roll (doc 20)

Pin MFA_ENCRYPTION_KEY (closes D13)

Generate on the workstation (do not commit the value):

Terminal window
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):

Terminal window
# On VPS
cd /opt/lyncareos
docker compose -f docker-compose.yml -f docker-compose.vps.yml \
--env-file .env.production --profile production \
up -d --force-recreate app scan_worker

Re-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 app and scan_worker always update together. They share backend/Dockerfile — the same image, different startup commands.

Terminal window
cd D:\Projects\LynCareOS
.\scripts\deploy.ps1

The script handles every step in sequence:

  1. Pre-flight (SSH, Docker, .env.production)
  2. npm run build in frontend/ (unless -SkipBuild)
  3. production-migration-preflight.ps1 -RunBackfillIfNeeded — VPS enc_version check; runs PHI backfill before V090 if needed
  4. Pre-deploy pg_dump on VPS
  5. Docker build + push to Hub
  6. VPS pull + restart app / scan_worker
  7. Smoke test (up to 120 s — large migration batches on startup)
  8. production-phi-pin.ps1 — append HKDF-derived PHI_* keys to VPS .env when 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:

Terminal window
.\scripts\deploy.ps1 -Tag v1.2.3 # give the release a meaningful name
.\scripts\deploy.ps1 -SkipBuild # push existing :latest without rebuilding

Helper scripts:

ScriptPurpose
.\migration-audit.ps1 -Target Vps -NonInteractiveRepo vs VPS schema_migrations (read-only)
.\scripts\production-migration-preflight.ps1enc_version counts; optional backfill
.\scripts\production-phi-pin.ps1Pin PHI_ENCRYPTION_KEY / PHI_BLIND_INDEX_KEY on VPS
.\scripts\dev-phi-pin.ps1Pin same keys in backend/.env (dev / lyncareos_dev)

init_db() applies pending migrations on every app startup (not a separate operator step):

Terminal window
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.

Pass the previous tag with -SkipBuild (no rebuild needed — the old image is still on Docker Hub):

Terminal window
.\scripts\deploy.ps1 -SkipBuild -Tag deploy-20260519-1100

Find previous tag names in Docker Hub: https://hub.docker.com/r/magna123456/lyncareos/tags

The script will:

  1. Push the old tag to Docker Hub (it’s already there, so the push is instant)
  2. Update APP_IMAGE on the VPS to the old tag
  3. Pull and recreate containers (--redeploy skips pg_restore)
  4. 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:

  1. Roll back the app image to the previous tag (see above) — the old code works with the old schema.
  2. On the VPS, inspect the broken migration:
Terminal window
docker logs --tail=80 lyncareos-app-1 2>&1 | grep -i migrat
  1. Connect to the database and manually check the migration table:
Terminal window
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;"
  1. 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:
Terminal window
# 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
  1. Fix the migration SQL, re-build and re-deploy with a new tag.

Rule: Never delete rows from schema_migrations unless 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).

ItemValue
Tunnel IDc0396e69-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
Ingressapp.lyncareos.com → http://localhost:8020
DNSapp CNAME c0396e69-….cfargotunnel.com (already configured — no change needed)

Check tunnel status (on VPS):

Terminal window
systemctl status cloudflared --no-pager -n 10

Restart after config change (on VPS):

Terminal window
systemctl restart cloudflared
sleep 3
systemctl is-active cloudflared # expect: active

If 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.ps1 on 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.

Terminal window
# Fresh pg_dump on VPS + pull to backups\
.\scripts\vps-production-backup.ps1
# Wrapper (same behaviour)
.\scripts\pull-vps-backup-to-workstation.ps1

Log: 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):

Terminal window
TS=lyncareos_$(date +%Y%m%d_%H%M%S).dump
docker exec lyncareos-postgres-1 pg_dump -U lyncare -d lyncareos --format=custom > /tmp/$TS
ls -lh /tmp/$TS

15.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.

WhenAction
Each deploy.ps1Pre-deploy VPS dump + post-deploy workstation pull (built in)
Weekly (this PC)vps-production-backup.ps1
At scaleVPS cron + rclone → B2 (roadmap A8)

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 Dev and -Target Vps -NonInteractive show 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)

StepActionPass?
1Take a fresh custom-format dump (§15.1) — note filename and size
2Create lyncareos_restore_test
3pg_restore dump into test DB
4Compare users / tenants counts: production vs test
5Spot-check one known tenant or user exists in test DB
6Drop lyncareos_restore_test (cleanup)
7Optional: copy dump off-box via scp to backups\ on workstation

Commands — test restore (non-destructive)

Terminal window
# 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 production
docker 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 database
docker 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:

Terminal window
# From repo root on the operations host — does NOT replace the VPS drill above
.\db-backup.ps1 -Target Production

A5 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):

Terminal window
# DESTRUCTIVE — production data is overwritten
docker 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 app
docker 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_worker

16. 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”
  1. SSH into VPS: ssh -i "$env:USERPROFILE\.ssh\lyncareos_vps" root@134.199.173.206
  2. Check app responds locally: curl -s -o /dev/null -w "HTTP %{http_code}\n" http://127.0.0.1:8020/api/billing/tiers
  3. If 200: check cloudflared — systemctl status cloudflared; restart if needed.
  4. If not 200: check app logs — docker logs --tail=60 lyncareos-app-1
  5. Cloudflare DNS: confirm app CNAME still points to c0396e69-….cfargotunnel.com.
  1. docker logs --tail=100 lyncareos-app-1 — look for the error on startup.
  2. Common causes: bad env var (SECRET_KEY, DATABASE_URL, Stripe key), Postgres unavailable, migration failure.
  3. Compare env vars against 04-ROADMAP §1.1 Secrets register.
  4. Restart after fixing: docker compose -f docker-compose.yml -f docker-compose.vps.yml --env-file .env.production --profile production restart app
Terminal window
df -h /
docker system prune --volumes # removes stopped containers, unused images, build cache

Never run docker volume prune — it would delete lyncare_pg_data.

16.4 Disk full — block volume (/data/pg)

Section titled “16.4 Disk full — block volume (/data/pg)”
Terminal window
df -h /data/pg

Resize the DigitalOcean volume in the control panel (no downtime for ext4 online resize), then:

Terminal window
resize2fs /dev/sda # (or whatever device /data/pg is mounted on — check with `lsblk`)

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)”
  1. Provision a new DigitalOcean droplet in Sydney.
  2. Attach the same 50 GB block volume (lyncareos-pg-data) — data survives a Droplet rebuild.
  3. Run vps-bootstrap-syd1.sh on the new Droplet.
  4. Copy .env.production, compose files, and tunnel credentials from workstation.
  5. Run vps-pull-and-start.sh (skips pg_restore if DB volume intact; uses --redeploy).
  6. Verify https://app.lyncareos.com responds.

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:

Terminal window
# Connect from workstation
ssh -i "$env:USERPROFILE\.ssh\lyncareos_vps" root@134.199.173.206
Terminal window
# ── 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 5
systemctl 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/pg
docker system df

Routine rolling deploy — from workstation (see §13):

Terminal window
# 1. Build and push new image
$tag = "build-$(Get-Date -Format 'yyyyMMdd')"
.\scripts\build-and-push.ps1 -HubUser magna123456 -Tag $tag
# 2. Backup
ssh -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 + restart
ssh -i "$env:USERPROFILE\.ssh\lyncareos_vps" root@134.199.173.206 `
"bash /opt/lyncareos/scripts/vps-pull-and-start.sh --redeploy"
# 5. Verify
Invoke-WebRequest -Uri "https://app.lyncareos.com/api/billing/tiers" -UseBasicParsing | Select-Object StatusCode

18. 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.

EventREINDEX required?
deploy.ps1 / app image roll only (containers updated, host OS unchanged)No
VPS OS or glibc upgrade on lyncareos-prod-syd1Yes — mandatory before closing the change
Workstation OS upgrade affecting Docker Postgres used for --profile production rehearsalYes on that Docker database when non-ASCII sort is used in tests
Native dev Postgres on Windows after major OS upgradeRecommended if you rely on ORDER BY on non-ASCII columns in dev
  • 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.ps1 when 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)”
Terminal window
# 1. Confirm Postgres is up
docker 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:

Terminal window
curl.exe -s -o NUL -w "%{http_code}" https://app.lyncareos.com/api/billing/tiers

Spot-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:

Terminal window
docker exec lyncareos-postgres-1 psql -U lyncare -d lyncareos -v ON_ERROR_STOP=1 -c "REINDEX DATABASE lyncareos;"