Files
dyolink/infrastructure/BACKUP.md

17 KiB
Raw Permalink Blame History

Manual database backup (nudentic.ir)

Copy-paste runbook for the production Postgres database. Use it when you need a dump in a hurry, a copy of production data on your Mac or the Windows staging PC, or a restore after something has gone wrong.

A dump is one file that contains the dyolink_db tables: users, patients, appointments, treatments, lab cases, billing, and so on. Taking a dump does not stop the site. Postgres reads a consistent snapshot while the app keeps running.

The dump does not contain photo or case-file bytes. Those files live on disk under uploads/. The database only stores the file name and the path. After a restore, the case row is back; opening the file still needs the file on disk.

Names

What Value
SSH dyolink@185.243.48.140
Server directory /opt/dyolink/infrastructure
Production Postgres container dyolink_db_prod
Database dyolink_db
Dump folder on the server /opt/dyolink/infrastructure/database/backups
Same folder inside the container /backups
Copy on the Mac ~/Documents/dental/nudentic-backups/
Copy on the Windows staging PC C:\dyolink\nudentic-backups
Local Postgres container dyolink-postgres-dev

The container already has POSTGRES_USER and POSTGRES_DB. Do not type the password, and do not print database.env.

Keep dump files private. They contain patient and account data. Do not commit them, and do not put them inside the git repo. ~/Documents/dental/nudentic-backups/ and C:\dyolink\nudentic-backups are outside the repo.

Do not

  • Do not run infrastructure/scripts/manage.sh backup. It uses -U postgres. Production has no postgres role; the user is dyolink_user.
  • Do not run docker volume rm dyolink_postgres_data_prod or docker volume prune. That deletes the live database.
  • Do not run the scp copy while your prompt is dyolink@srv…. That copies the file onto the server again. scp runs on the Mac, where the prompt is rameen@….

Automatic backups (three times a day)

The server keeps a new dump at three Iran times (Asia/Tehran, UTC+3:30). Each run adds a file. It does not replace the previous one. Files named nudentic_YYYYMMDD_HHMMSS.dump that are older than 3 days are deleted. That is about 9 files. nudentic_before_restore_*.dump is never deleted by this job.

Iran time What it captures
02:00 The previous day, after the clinic is closed
11:00 Morning work
16:00 Most of the afternoon

The longest gap is overnight, from 16:00 to 02:00. Rows saved in that gap are only in the live database until the next file. These files sit on the same disk as the database. The Windows staging PC copies each dump off that disk 30 minutes later. The Mac copy in section 2 is the other off-site copy. Filenames use UTC, the same clock as the first manual dump.

The script is scripts/backup-prod-db.sh. A git tag deploy does not copy it, so put it on the server once from the Mac:

scp infrastructure/scripts/backup-prod-db.sh dyolink@185.243.48.140:/opt/dyolink/infrastructure/scripts/
ssh dyolink@185.243.48.140 'chmod +x /opt/dyolink/infrastructure/scripts/backup-prod-db.sh && /opt/dyolink/infrastructure/scripts/backup-prod-db.sh'

The last command writes one dump immediately so you can see it in database/backups before cron is installed.

Cron is also one time, on the server, as the dyolink user. Check the server clock first:

date

If that time is already Iran time (offset +0330), install these three lines:

(crontab -l 2>/dev/null | grep -v backup-prod-db.sh; cat <<'EOF'
0 2 * * * /opt/dyolink/infrastructure/scripts/backup-prod-db.sh >> /opt/dyolink/infrastructure/database/backups/backup.log 2>&1
0 11 * * * /opt/dyolink/infrastructure/scripts/backup-prod-db.sh >> /opt/dyolink/infrastructure/database/backups/backup.log 2>&1
0 16 * * * /opt/dyolink/infrastructure/scripts/backup-prod-db.sh >> /opt/dyolink/infrastructure/database/backups/backup.log 2>&1
EOF
) | crontab -

If date shows UTC, the same Iran times are 22:30, 07:30, and 12:30 UTC:

(crontab -l 2>/dev/null | grep -v backup-prod-db.sh; cat <<'EOF'
30 22 * * * /opt/dyolink/infrastructure/scripts/backup-prod-db.sh >> /opt/dyolink/infrastructure/database/backups/backup.log 2>&1
30 7 * * * /opt/dyolink/infrastructure/scripts/backup-prod-db.sh >> /opt/dyolink/infrastructure/database/backups/backup.log 2>&1
30 12 * * * /opt/dyolink/infrastructure/scripts/backup-prod-db.sh >> /opt/dyolink/infrastructure/database/backups/backup.log 2>&1
EOF
) | crontab -

Confirm with crontab -l. Putting this in git does not turn cron on. On nudentic the UTC lines above are already installed, so date on that server prints UTC and the jobs run at 22:30, 07:30, and 12:30 UTC.


1. Take a backup

The site stays up. SSH in:

ssh dyolink@185.243.48.140

On the server (dyolink@srv…):

cd /opt/dyolink/infrastructure
mkdir -p database/backups
docker exec dyolink_db_prod sh -c \
  'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc -f /backups/nudentic_$(date +%Y%m%d_%H%M%S).dump'
ls -lh database/backups
docker exec dyolink_db_prod sh -c 'pg_restore -l /backups/nudentic_*.dump | head -40'

ls -lh must be run from /opt/dyolink/infrastructure, or use ls -lh with no extra path if you are already inside database/backups.

A good dump is larger than a few kilobytes. The pg_restore -l list should name dbname: dyolink_db and tables such as patients and lab_cases. A file of a few bytes means the dump failed.

Leave this SSH session open if you still need it. The next step is a new terminal on the Mac.


2. Copy the dump to the Mac

Open a terminal on the Mac. The prompt must be rameen@…, not dyolink@srv…. From the repo:

cd /Users/rameen/Documents/dental/dyolink
./infrastructure/scripts/copy-prod-backup.sh

It asks for the server password once and does not save it. It copies every .dump file from the server backup folder into ~/Documents/dental/nudentic-backups/ and prints the list. A good file is larger than a few kilobytes (the first successful dump was 574K).

Every day at 17:00

Run that script once a day at 17:00 Iran time, after the 16:00 server dump. One run copies every dump still on the server, including the 02:00 and 11:00 files, so it does not need to run three times. The Mac clock must be Iran time. If the Mac is asleep at 17:00, that run is skipped; the files stay on the server for 3 days, so the next afternoon the Mac is awake still copies them.

At 17:00 a password box appears on the Mac. Type the server password and click Copy. It is not saved. You must be logged in so the box can appear. Cancel skips that day’s copy.

Install the 17:00 job (this does not happen from git by itself):

mkdir -p ~/Documents/dental/nudentic-backups ~/Library/LaunchAgents
cp infrastructure/launchd/ir.nudentic.copy-prod-backup.plist ~/Library/LaunchAgents/
launchctl bootout gui/$(id -u) ~/Library/LaunchAgents/ir.nudentic.copy-prod-backup.plist 2>/dev/null || true
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/ir.nudentic.copy-prod-backup.plist

Output goes to ~/Documents/dental/nudentic-backups/copy.log.


Copy the dumps to the Windows staging PC

The staging PC pulls the same folder three times a day, 30 minutes after each production dump. One run copies every .dump still on the server and skips a file that is already in C:\dyolink\nudentic-backups. If the PC is off at 11:30, that run starts when the PC is next on, and the 16:30 run still copies the 11:00 file while production is up.

Iran time What it copies
02:30 The 02:00 dump
11:30 The 11:00 dump
16:30 The 16:00 dump

The folder on the PC mirrors the server folder. After a run where every copy succeeded, a nudentic_*.dump on the PC that is no longer on the server is deleted (about 3 days of dumps are left). If the server list is empty or any copy fails, nothing is deleted. The Mac copy is the longer archive. This stores files only. It does not load them into the staging database, and it does not change the production server.

The script is scripts/copy-prod-backup.ps1. It reads the production SSH password from C:\dyolink\secrets\nudentic-ssh-password.txt. A scheduled task has no person to type it. The password file is the full dyolink login. Do not commit it. SSH is started hidden with -v. On the staging PC a hidden run without -v waits forever and copy.log stays on Starting copy from production.; with -v it finishes in about 8 seconds (the password helper needs that long to start).

A deploy does not install this. On the Windows PC, from a checkout of the repo:

New-Item -ItemType Directory -Force -Path C:\dyolink\scripts, C:\dyolink\nudentic-backups
Copy-Item infrastructure\scripts\copy-prod-backup.ps1, infrastructure\scripts\copy-prod-backup-askpass.cmd C:\dyolink\scripts\

Put the production SSH password in C:\dyolink\secrets\nudentic-ssh-password.txt on one line. No quotes.

The first run writes C:\dyolink\scripts\copy-prod-backup-askpass.exe next to the cmd file. Windows OpenSSH cannot start a .cmd as the password prompt, so that exe runs the cmd and passes the password through. It is created on the PC. It is not in git.

Check the PC clock:

Get-Date -Format 'yyyy-MM-dd HH:mm:ss zzz'

If the offset is +03:30, register 02:30, 11:30, and 16:30. The task runs as the current Windows user whether or not anyone is logged in. That user must be able to read C:\dyolink\secrets. The password it asks for is the Windows login, so the task can open the network connection. It is not the server password.

Use the full powershell.exe path and a quoted -File path. powershell.exe alone, or a -File path Windows cannot open, finishes with 4294770688 (0xFFFD0000) and never runs the script. The limit is 45 minutes so a stuck copy cannot block the later runs for three days.

$powershell = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
$scriptPath = 'C:\dyolink\scripts\copy-prod-backup.ps1'
$action = New-ScheduledTaskAction -Execute $powershell -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$scriptPath`"" -WorkingDirectory 'C:\dyolink\scripts'
$triggers = @(
  (New-ScheduledTaskTrigger -Daily -At '02:30'),
  (New-ScheduledTaskTrigger -Daily -At '11:30'),
  (New-ScheduledTaskTrigger -Daily -At '16:30')
)
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 45)
$secure = Read-Host 'Windows account password (lets the task run when nobody is logged in)' -AsSecureString
$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
$windowsPassword = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
Register-ScheduledTask -TaskName 'Nudentic copy prod backup' -Action $action -Trigger $triggers -Settings $settings -User "$env:USERDOMAIN\$env:USERNAME" -Password $windowsPassword -Force

If Get-Date shows UTC (+00:00), production’s jobs are 22:30, 07:30, and 12:30 UTC. Use 23:00, 08:00, and 13:00 in $triggers instead.

Already on the staging PC

The task name is Nudentic copy prod backup. scripts/copy-prod-backup.ps1 only copies files. It does not create this task. Creating it is the Register-ScheduledTask block above, run once on the PC.

On the staging PC it is already registered as Administrator. The clock there is Iran time (+03:30), and the triggers are 02:30, 11:30, and 16:30. Running that block again replaces the same task.

See it:

Get-ScheduledTask -TaskName 'Nudentic copy prod backup' | Format-List TaskName, State
Get-ScheduledTaskInfo -TaskName 'Nudentic copy prod backup' | Format-List LastRunTime, LastTaskResult, NextRunTime

State: Ready means it is scheduled. LastTaskResult 267011 and a LastRunTime in 1999 mean it has never run. 0 means the last copy finished. 4294770688 (0xFFFD0000) means Windows did not open the script path. Re-register with the block above, then run the script by hand.

Run it now without waiting for the next clock time:

Start-ScheduledTask -TaskName 'Nudentic copy prod backup'

Then read C:\dyolink\nudentic-backups\copy.log. A good line says Copied nudentic_….dump. A second run says Already present. The first run also stores the production host key in known_hosts in that folder. A .dump larger than a few kilobytes in C:\dyolink\nudentic-backups is a good file.

You can also run the script by hand:

powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\dyolink\scripts\copy-prod-backup.ps1

3. Load the dump into the local database

This deletes the current local dyolink_db and replaces it with the dump. Production is not touched.

Stop the local API first (npm run start:dev in backend/). Postgres itself stays up.

From backend/, start local Postgres if it is not already running:

cd /Users/rameen/Documents/dental/dyolink/backend
docker compose -f docker-compose.postgres.yml up -d

The container name is dyolink-postgres-dev. DATABASE_URL in backend/.env should already point at localhost and database dyolink_db.

On the Mac, copy the dump into that container and replace the local database. Change the filename if yours is different.

docker cp ~/Documents/dental/nudentic-backups/nudentic_YYYYMMDD_HHMMSS.dump dyolink-postgres-dev:/tmp/nudentic.dump
docker exec dyolink-postgres-dev sh -c 'psql -U "$POSTGRES_USER" -d postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '\''dyolink_db'\'' AND pid <> pg_backend_pid();"'
docker exec dyolink-postgres-dev sh -c 'dropdb -U "$POSTGRES_USER" --if-exists dyolink_db && createdb -U "$POSTGRES_USER" dyolink_db'
docker exec dyolink-postgres-dev sh -c 'pg_restore -U "$POSTGRES_USER" -d dyolink_db --no-owner --no-acl /tmp/nudentic.dump'
docker exec dyolink-postgres-dev sh -c 'psql -U "$POSTGRES_USER" -d dyolink_db -c "\dt"'

pg_restore may print warnings. If \dt lists tables such as patients, lab_cases, and users, the restore worked.

Start the API and the frontend the way you usually do. Sign in with a production account: the password hashes came with the dump. Local .env secrets stay as they are.

Attachment links will not open files on the Mac, because those files were not in the dump.


4. Emergency: put a dump back on production

This replaces the live nudentic.ir database. Everything saved after that dump’s timestamp is gone. Run this only when you have decided the current production data should be discarded.

SSH in and go to the infrastructure directory:

ssh dyolink@185.243.48.140
cd /opt/dyolink/infrastructure

4a. Save the database you are about to replace. If the restore is wrong, this file is the way back.

docker exec dyolink_db_prod sh -c \
  'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc -f /backups/nudentic_before_restore_$(date +%Y%m%d_%H%M%S).dump'
ls -lh database/backups

4b. If the dump you want is only on the Mac, send it to the server first. Run this on the Mac, not inside SSH:

scp ~/Documents/dental/nudentic-backups/nudentic_YYYYMMDD_HHMMSS.dump \
  dyolink@185.243.48.140:/opt/dyolink/infrastructure/database/backups/

4c. Stop the API so it cannot write during the restore. Postgres stays running.

docker compose -f docker-compose.prod.yml --env-file .env stop backend

4d. Load the chosen dump. Replace the filename with the dump you intend to keep (not the before_restore file, unless that is the one you want).

docker exec dyolink_db_prod sh -c 'psql -U "$POSTGRES_USER" -d postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '\''dyolink_db'\'' AND pid <> pg_backend_pid();"'
docker exec dyolink_db_prod sh -c 'dropdb -U "$POSTGRES_USER" --if-exists dyolink_db && createdb -U "$POSTGRES_USER" dyolink_db'
docker exec dyolink_db_prod sh -c 'pg_restore -U "$POSTGRES_USER" -d dyolink_db --no-owner --no-acl /backups/nudentic_YYYYMMDD_HHMMSS.dump'

4e. Start the API again.

docker compose -f docker-compose.prod.yml --env-file .env start backend

On startup the API runs prisma migrate deploy and the reference-data seed. That brings the schema in line with the running app if the app is newer than the dump. It does not delete the restored patients and cases.

4f. Check the site. Open https://nudentic.ir/api/health, then sign in and open a case you know was in that dump.

Case rows come back with the dump. Photo and case files on the server disk are left as they are. A database restore does not roll those files backward or forward.