#!/usr/bin/env bash # # On the server, next to the compose file, or with its directory as $1. One # snapshot of the database, taken through the running container, kept # alongside the others. # # bash backup.sh # into $APP_DATA/backups # 0 4 * * * bash /srv/swag/backup.sh >> /srv/swag/backup.log 2>&1 # # `VACUUM INTO` rather than copying the file: SQLite is in WAL mode, so the # .db on disk is missing whatever is still in the -wal, and `cp` of a live # database is a coin toss. VACUUM INTO takes a read lock, writes one # self-contained and compacted file, and never blocks a writer for long enough # to matter on a database of this size. # # Rename `app` and `APP_DATA` to your service's name. set -euo pipefail cd "${1:-$(dirname "$(readlink -f "$0")")}" # Same source of truth as the compose file and deploy.sh. DATA=$(sed -n 's/^[[:space:]]*APP_DATA=\([^#]*\).*/\1/p' .env | tail -1 | xargs || true) DATA=${DATA:-./data} KEEP=${KEEP:-14} stamp=$(date +%Y%m%d-%H%M%S) mkdir -p "$DATA/backups" docker compose exec -T app python -c " import sqlite3 db = sqlite3.connect('/data/app.db') db.execute('VACUUM INTO ?', ('/data/backups/app-$stamp.db',)) db.close() " gzip -f "$DATA/backups/app-$stamp.db" echo "$DATA/backups/app-$stamp.db.gz $(du -h "$DATA/backups/app-$stamp.db.gz" | cut -f1)" # Oldest first, everything past KEEP goes. Named by timestamp, so sorting the # names sorts them by age. ls -1 "$DATA"/backups/app-*.db.gz 2>/dev/null \ | sort \ | head -n -"$KEEP" \ | while read -r old; do rm -f "$old"; echo "removed $old"; done