# V1 and V2 on the same Ubuntu server **The AWS deployment is live. See [AWS-DEPLOYED.md](AWS-DEPLOYED.md) for its actual systemd services, paths, schedule and verification. It creates no server backup, retains no database snapshots, and leaves original uploads in place.** The instructions below describe the alternative Docker deployment template. **V1 is authoritative for imported accounts, workouts and videos.** The job snapshots both databases, then merges selected data into V2. It never replaces V2's database or writes to V1. | Hostname | Upstream | Database | Media | | --- | --- | --- | --- | | workouttv.vitalityfitnessva.com | Existing app, port 3000 | Existing `site/database.sqlite` | Existing `site/public/uploads` | | workouttv2.vitalityfitnessva.com | New container, localhost port 3001 | `/var/lib/vitfit-v2/vitfit.sqlite` | `/var/lib/vitfit-v2/uploads` | V2 has a separate Compose project, image, secret, storage directory and port. V1 keeps its existing process manager. Never mount the V1 database or uploads directory as V2's writable storage; deleting a video in V2 deletes its file. ## 1. Confirm the host layout The server is reachable as `ubuntu@34.228.59.242`, runs Ubuntu 24.04, and runs V1 under `vitfit.service` from `/home/ubuntu/site`. The Docker example below assumes the repository has been transferred to `/opt/VitFit` separately from the running V1 installation. Transfer application source, excluding `.env`, `node_modules`, databases, database sidecars, uploads and temporary files. Set production secrets on the host. Inspect existing services before installing or changing the proxy: ```bash lsb_release -ds sudo ss -ltnp sudo nginx -t sudo nginx -T docker compose version df -h timedatectl ``` If Apache or another proxy owns ports 80/443, adapt that setup before installing these Nginx files. Ensure port 3001 is free. Use the existing Docker installation; if absent, follow [Docker's Ubuntu installation instructions](https://docs.docker.com/engine/install/ubuntu/). Do not replace the current app's Node installation. The V2 container uses Node 24 from the [Node.js LTS release line](https://nodejs.org/en/about/previous-releases). ## 2. Prepare and start an empty V2 These commands initialize a fresh V2 environment for testing. They do **not** import V1 records. Existing accounts will work there after the selective sync in step 5 is run. ```bash cd /opt/VitFit/V2/deploy/coexist sudo install -d -m 0750 -o 1000 -g 1000 /var/lib/vitfit-v2 sudo install -d -m 0750 -o 1000 -g 1000 /var/lib/vitfit-v2/uploads /var/lib/vitfit-v2/tmp umask 077 cp -n .env.example .env openssl rand -hex 32 nano .env # Set V2_JWT_SECRET to the generated value; use a different secret from V1. docker compose config --quiet docker compose build --pull docker compose run --rm app node scripts/setup.js docker compose up -d docker compose ps curl --fail http://127.0.0.1:3001/health ``` Setup prompts for the organization, timezone, Owner and SystemAdmin. Use distinct V2 usernames that do not overlap V1 usernames. The importer refuses to merge an unmapped account by username. Set the organization timezone to `America/New_York`. Setup runs once. Imported V1 Admin accounts become additional V2 Owners. The database health value must be `ok`; investigate a disk warning before copying videos. Plan capacity for both media libraries and retained backups. The existing `scripts/migrate-v1-to-v2.js` is a one-time full upgrade, includes timers and other tables, and exits once an organization exists. It is **not** the selective daily sync. Do not point it at the live V1 database or use it for cron. ## 3. Route both names and enable Let's Encrypt Both DNS A records must point to the server's public IPv4 address. Any AAAA records must point to a working IPv6 address on this server. Allow inbound TCP 80 and 443 in both the server firewall and provider firewall; retain SSH access. Keep port 80 reachable for renewal. Do not expose port 3001 publicly. Back up the existing Nginx configuration, then install the V2 server block: ```bash sudo tar -czf "/root/nginx-before-vitfit-v2-$(date +%Y%m%d-%H%M%S).tgz" -C /etc nginx sudo install -m 0644 workouttv2.conf /etc/nginx/sites-available/workouttv2.conf sudo ln -s /etc/nginx/sites-available/workouttv2.conf /etc/nginx/sites-enabled/workouttv2.conf sudo nginx -t sudo systemctl reload nginx ``` Keep the current domain's existing server block. Only if it has none, install `workouttv.conf` the same way. Never enable duplicate blocks for a hostname. The supplied files bootstrap HTTP without referencing nonexistent certificates. After Certbot modifies them, preserve the installed files on later deployments. Use one Certbot installation. If it is already installed, reuse it. For a new installation, Ubuntu documents the snap distribution: ```bash sudo snap install --classic certbot sudo /snap/bin/certbot --nginx --redirect -d workouttv.vitalityfitnessva.com sudo /snap/bin/certbot --nginx --redirect -d workouttv2.vitalityfitnessva.com sudo /snap/bin/certbot renew --dry-run sudo systemctl list-timers --all | grep -i certbot sudo nginx -t curl -I https://workouttv.vitalityfitnessva.com curl --fail https://workouttv2.vitalityfitnessva.com/health ``` For an existing non-snap installation, use its `certbot` executable instead. Supply the operational email when prompted. These commands request a separate certificate for each name; Certbot's scheduled renewal handles both. Verify its timer (or existing cron installation) is enabled, and that the dry run succeeds. The Nginx plugin reloads Nginx after renewal. Do not add a second renewal scheduler. See [Ubuntu's TLS guide](https://ubuntu.com/server/docs/how-to/security/obtain-tls-certificates/) and [Certbot's Nginx instructions](https://certbot.eff.org/instructions?os=snap&ws=nginx). Validate login, video upload/playback, workout creation and a Socket.IO display connection on V2. Check the current site still logs in and plays videos. ## 4. Database snapshot utility `snapshot.py` uses SQLite's online backup API, includes committed WAL data, validates the resulting database and refuses to overwrite an existing file. This is a backup primitive, **not a selective importer or synchronizer**. The full snapshot contains sensitive account hashes and all tables; only the agreed tables should be imported from it. Keep backups outside web directories. ```bash sudo install -d -m 0700 /var/backups/vitfit sudo python3 snapshot.py /ACTUAL/V1/site/database.sqlite "/var/backups/vitfit/v1-$(date +%Y%m%d-%H%M%S).sqlite" sudo python3 snapshot.py /var/lib/vitfit-v2/vitfit.sqlite "/var/backups/vitfit/v2-$(date +%Y%m%d-%H%M%S).sqlite" ``` Use the real V1 path in place of the placeholder. Never `cp` an active SQLite database: recent transactions can reside in its WAL. See the [SQLite backup API documentation](https://www.sqlite.org/backup.html). Media files require their own backup; a database snapshot does not contain them. ## 5. Selective morning sync: V1 wins `sync.py` requires Python 3.9+ on Ubuntu. It runs with a non-overlapping lock and takes SQLite snapshots of both databases before each attempt. It reads V1's snapshot, stages and hashes video files, validates the merge on the V2 backup, then commits selected changes and ID mappings together in live V2. No restart is required; V2 writes may briefly wait for the SQLite transaction to finish. V2's normal startup migrations create/upgrade its schema; daily sync transforms the selected V1 records into that schema without running V1's full upgrade. | Data | Daily behavior | | --- | --- | | Accounts | Sync username, bcrypt password and role; `Admin` maps to `Owner`, `Coach` to `Coach`. Existing V1 accounts are active in V2. Password, role or activation changes invalidate V2 sessions. | | Deleted V1 accounts | Disable the mapped V2 account and revoke device tokens; keep references/history. | | Standard and Crossfit workouts | Sync contents, dates and repetition counts; remap video IDs. Delete mapped workouts removed from V1. | | Videos | Copy actual files using immutable content-based names; sync metadata and remap IDs. Delete mapped metadata removed from V1 unless V2 workouts/client assignments still reference it. | | Categories | Add V1 categories and category names used by videos. Retain existing categories to preserve V2-only usage. | | V2-only data | Preserve organization, branding, profiles, timers, clients, assignments, calendars, audit history and accounts created only in V2. | Edits to **imported** account credentials/roles/activation, workouts and video metadata in V2 are overwritten at the next sync. Records created only in V2 remain there and never flow back to V1. V2-only profile fields on imported accounts remain unchanged. Keep routine editing of shared content in V1. Changes can take about 24 hours to appear in V2. The `V1SyncMap` and `V1SyncConfig` tables belong to the importer. Retain them in backups. Do not point this importer at a previously fully migrated V1 copy: it does not guess account mappings and will stop on username collisions. Use a fresh V2 setup above, or prepare an explicit mapping for an existing V2 database. Source identity is pinned to its absolute path and selected organization. Missing/changed video files, broken source workout references, account name collisions or organization mismatches abort the database merge. Original source media never changes. Old imported file versions are retained, including files published before a failed commit; retrying is safe. This makes rollback possible but requires disk monitoring. A V2 deletion concurrent with file publication can still remove its file; avoid editing imported videos while the morning job runs. Configure actual paths and IDs on the host: ```bash cd /opt/VitFit/V2/deploy/coexist id ubuntu # The cron user must match the container's UID 1000 and have read access to V1. sudo install -d -m 0700 -o ubuntu -g ubuntu /var/backups/vitfit-sync sudo install -m 0600 -o ubuntu -g ubuntu sync.example.json /etc/vitfit-v2-sync.json sudo -u ubuntu nano /etc/vitfit-v2-sync.json # Set actual v1_db/v1_uploads, organization_id and an active V2 creator_id. sudo install -m 0600 -o ubuntu -g ubuntu /dev/null /var/log/vitfit-v2-sync.log sudo -u ubuntu python3 sync.py --config /etc/vitfit-v2-sync.json # Review the dry-run counts, then apply the same configuration: sudo -u ubuntu python3 sync.py --config /etc/vitfit-v2-sync.json --apply ``` If Ubuntu's UID is not 1000, adapt the container user and data ownership before running sync. Do not run live sync as root: root-owned SQLite sidecars can prevent the container from writing. Each run creates a mode-0700 backup directory with `v1.sqlite`, `v2-before.sqlite` and, on success, `result.json`. Dry-runs leave the live database unchanged and keep their snapshots for review. Video staging needs temporary free space for one complete V1 video library in addition to both apps' stored media. Retain at least 30 days of successful backups and arrange pruning and off-server copies; this package deliberately does not delete backups or media. Run the script as the same user for manual and cron runs; the lock is in `backup_dir/sync.lock`. Lock contention, validation failures, missing files and database failures return a nonzero exit status. Successful reports contain counts, never usernames or password hashes. A `Videos.retained_referenced` count means a deleted V1 video is still needed by V2; resolve those references if you want its metadata removed on the next run. After testing both apps, install the job and log rotation: ```bash timedatectl sudo install -m 0644 vitfit-v2-sync.cron /etc/cron.d/vitfit-v2-sync sudo install -m 0644 vitfit-v2-sync.logrotate /etc/logrotate.d/vitfit-v2-sync sudo systemctl enable --now cron ``` The supplied cron entry runs at **05:00 in the server's timezone**. Adjust before installing if the AWS server uses UTC and a different local morning is wanted; the organization timezone does not control cron. Files must use Unix LF line endings. Monitor `/var/log/vitfit-v2-sync.log` and alert if no successful applied `result.json` appears within 26 hours. Actual alert delivery depends on the server's monitoring/mail setup; redirecting logs alone does not send alerts. ## Rollback and updates Disable `/etc/cron.d/vitfit-v2-sync` before restoring or retiring V2; wait for any active sync to finish. To stop V2, run `docker compose down` here. Its bind-mounted data remains and V1 continues running. Disable only the V2 Nginx symlink if retiring the V2 hostname, then test and reload Nginx. Keep the V1 server block and its certificate intact. For a V2 update, snapshot its DB and back up uploads, retain the previous image, then rebuild and run `docker compose up -d`. Schema rollback may require restoring the matching backup with V2 stopped, so retain both image and data together. Local tests: `python -m unittest discover -s V2/deploy/coexist -p 'test_*.py'`. Sync integration tests use the real V2 migrations and require Node plus installed V2 dependencies. All test data is disposable; tests never open the app databases.