Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Borg

How to Set Up Automatic Database Backups on a VPS

By Freedom251 Team · · 7 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The dependable pattern is a database-native dump, a timestamped and encrypted archive, an upload to storage outside the VPS, automatic retention, failure alerts, and scheduled restore tests. A snapshot or a successful upload listing is not enough: you need to prove that a copy can be opened and used to start a database.

This guide covers PostgreSQL and MySQL, cron and systemd scheduling, Restic and Borg repositories, least-privilege credentials, lock files, retention, monitoring, and recovery drills. Adapt the commands to your database name, operating-system user, storage backend, and recovery objectives.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Define what the backup must recover

Before writing a script, decide how much data you can lose and how quickly the service must return. The recovery point objective (RPO) is the maximum acceptable data loss. A nightly dump can lose almost a day of changes; hourly dumps reduce that window but consume more storage and database I/O. The recovery time objective (RTO) is the time allowed to restore service. A logical dump is usually portable and easy to inspect, but restoring a very large database can take substantially longer than restoring a prepared base backup.

Write down the answers for each database:

  • Which databases, schemas, roles, routines, and extensions must be included?
  • What is the maximum tolerable loss of committed transactions?
  • How long may the application be offline during recovery?
  • Where will the off-site copy live if the VPS, account, disk, or region is unavailable?
  • Who receives alerts and who holds the encryption or repository key?

Keep logs outside the directory containing local backup files. A failed disk or an accidental deletion must not remove both the evidence and the only copy.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Choose a backup method

PostgreSQL’s documentation describes three distinct approaches. SQL dumps are portable and straightforward to restore. Filesystem-level backups can be faster for some workloads, but they depend on compatible storage and correct shutdown or consistency procedures. Continuous archiving combines a base backup with WAL archiving and supports point-in-time recovery (PITR).

Method Recovery characteristics Operational considerations
Logical dump (pg_dump or mysqldump) Portable, inspectable, and simple to restore; recovery is to the time of the dump Can be slow to restore for very large databases; does not by itself provide continuous PITR
Filesystem or base backup Can shorten restore time for large datasets Requires database-specific consistency handling and compatible storage procedures
Continuous archiving with PITR Allows recovery to a precise time when a base backup and WAL archiving are available Needs more storage, monitoring, and operational expertise

For a small or medium application, begin with a tested logical dump sent off-site. Move to a base-backup-plus-WAL design when the database is too large for the required RTO or when losing more than a few minutes of transactions is unacceptable. A snapshot alone is not a substitute for a consistent database backup unless the database engine and storage procedure explicitly support it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prepare the VPS and backup identity

Create a protected working layout

Use a root-owned script in /usr/local/sbin/db-backup, or a dedicated backup service account with only the permissions it needs. Keep temporary archives in a directory with restrictive permissions and place logs in a separate location such as /var/log/db-backup. Do not write archives into a web server’s document root.

sudo install -o root -g root -m 700 /dev/null /usr/local/sbin/db-backup
sudo install -d -o root -g root -m 700 /var/lib/db-backup
sudo install -d -o root -g root -m 700 /var/log/db-backup

Use a separate database identity for backups. Grant it the minimum read, metadata, and lock permissions required by the dump tool; do not reuse the application’s unrestricted owner account. Store credentials in a protected client file or secret manager rather than on a command line, where they can appear in process listings or shell history.

Protect transport and keys

Use encrypted transport to the remote repository and keep the repository key separately protected. If the VPS is compromised, an attacker should not automatically obtain both the encrypted archives and the key needed to decrypt them. Keep at least one copy outside the VPS account or host. Test access using the same off-site destination that production recovery would use, not merely a local cache.

Build a PostgreSQL backup

Choose the dump scope

pg_dump exports one database. It includes that database’s schema and data, but not cluster-wide roles or tablespaces. Use pg_dumpall --globals-only (or a full pg_dumpall where appropriate) when roles, grants, and other global objects are part of recovery. For a larger PostgreSQL installation that needs point-in-time recovery, configure a base backup and WAL archiving; do not rely only on periodic dumps.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Store credentials without exposing them

A PostgreSQL client password file should be readable only by its owner. For a root-run script, create a root-owned file such as /root/.pgpass with mode 600, or point PGPASSFILE to an equivalently protected path. A secret manager is preferable when your infrastructure already provides one.

Example dump script

The following pattern creates a timestamped compressed dump, refuses to run concurrently, and exits nonzero when any stage fails. Replace the connection values and repository command with your environment.

#!/bin/sh
set -eu
umask 077

LOCK=/run/lock/postgres-backup.lock
DEST=/var/lib/db-backup/postgres
LOG=/var/log/db-backup/postgres.log
STAMP=$(date -u +%Y%m%dT%H%M%SZ)
DB=appdb
OUT="$DEST/${DB}-${STAMP}.sql.gz"

mkdir -p "$DEST"
exec 9>"$LOCK"
flock -n 9 || { echo "backup already running" >&2; exit 1; }

trap 'status=$?; echo "$(date -u) exit=$status" >> "$LOG"; exit $status' EXIT

echo "$(date -u) starting $DB" >> "$LOG"
pg_dump --format=plain --no-owner --no-privileges "$DB" | gzip -9 > "$OUT"
test -s "$OUT"

# Upload with your repository client, then verify the uploaded snapshot.
# restic backup "$OUT" --tag postgres

find "$DEST" -type f -name '*.sql.gz' -mtime +14 -delete
echo "$(date -u) completed $OUT" >> "$LOG"

Run a separate globals export if roles and grants are needed, and upload it with the database dump. Keep the database and globals files associated with the same timestamp so a restore operator knows which set belongs together.

Build a MySQL backup

For MySQL, a logical workflow uses mysqldump. A common transactional setup uses --single-transaction for InnoDB tables, while also exporting routines and events when the application depends on them. Triggers are normally included, but state the option explicitly in scripts so a future change is visible. Tables using nontransactional engines need additional consistency planning; --single-transaction does not make those tables consistent.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a protected MySQL option file, for example /root/.my.cnf with mode 600, instead of placing a password in the command. The account should have only the privileges required to read the selected databases and metadata.

#!/bin/sh
set -eu
umask 077

LOCK=/run/lock/mysql-backup.lock
DEST=/var/lib/db-backup/mysql
LOG=/var/log/db-backup/mysql.log
STAMP=$(date -u +%Y%m%dT%H%M%SZ)
DB=appdb
OUT="$DEST/${DB}-${STAMP}.sql.gz"

mkdir -p "$DEST"
exec 9>"$LOCK"
flock -n 9 || { echo "backup already running" >&2; exit 1; }

trap 'status=$?; echo "$(date -u) exit=$status" >> "$LOG"; exit $status' EXIT

echo "$(date -u) starting $DB" >> "$LOG"
mysqldump --single-transaction --routines --events --triggers --hex-blob "$DB" | gzip -9 > "$OUT"
test -s "$OUT"
# Upload and verify with your repository client here.
# restic backup "$OUT" --tag mysql

find "$DEST" -type f -name '*.sql.gz' -mtime +14 -delete
echo "$(date -u) completed $OUT" >> "$LOG"

For MySQL replication or very large datasets, evaluate a physical or engine-specific backup method against your RTO. A logical dump remains useful as a portable fallback even when a faster physical copy is your primary recovery path.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Send archives to off-site storage

Restic repositories

Restic is an encrypted repository client that supports S3 and S3-compatible storage, SFTP, Azure Blob, Google Cloud Storage, and other backends. It does not provide its own scheduler, so invoke it from cron or a systemd timer. Initialize the repository once, store its password outside the VPS or in a protected secret service, and restrict the storage credentials to the target bucket or path.

After creating a dump, run a repository backup tagged with the database and environment, then check that the snapshot is visible. A successful upload command should be treated as a prerequisite for verification, not as proof that a restore will work.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
restic -r "$RESTIC_REPOSITORY" backup /var/lib/db-backup/postgres 
  --tag postgres --tag production
restic -r "$RESTIC_REPOSITORY" snapshots --tag postgres
restic -r "$RESTIC_REPOSITORY" check

Run repository maintenance and pruning according to your retention policy. Keep enough snapshots to cover daily operations, weekly incidents, and monthly or long-term recovery requirements; do not prune the only copy before a newer copy has been verified.

Borg repositories

Borg provides deduplication, compression, authenticated encryption, and repositories reachable over SSH. A typical policy keeps several daily archives, several weekly archives, and several monthly archives. Express that policy with borg prune, then run repository checks on a schedule that does not overlap with backups.

borg create --stats --compression zstd 
  ssh://backup-user@backup-host/./repo::'{hostname}-{now}' 
  /var/lib/db-backup/postgres /var/lib/db-backup/mysql
borg prune --list --keep-daily=7 --keep-weekly=4 --keep-monthly=12 
  ssh://backup-user@backup-host/./repo

Use a dedicated SSH key restricted to the repository and, where supported, a forced command or restricted account. Keep the Borg passphrase separately protected from the VPS and document the recovery process for authorized operators.

Schedule without overlapping runs

Cron

Cron is adequate for a straightforward schedule. Edit root’s crontab with sudo crontab -e. This example runs at 02:15 UTC every day and writes standard output and errors to the external log:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
15 2 * * * /usr/local/sbin/db-backup >>/var/log/db-backup/cron.log 2>&1

Use the server’s actual timezone deliberately; UTC avoids surprises during daylight-saving changes. The script’s flock prevents a slow dump from overlapping the next invocation. If your system lacks flock, use an equivalent atomic lock mechanism and remove stale locks safely.

systemd timer

Systemd provides explicit dependencies, journal logging, and missed-run behavior. Create /etc/systemd/system/db-backup.service:

[Unit]
Description=Database backup

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/db-backup

Then create /etc/systemd/system/db-backup.timer:

[Unit]
Description=Run database backup daily

[Timer]
OnCalendar=*-*-* 02:15:00 UTC
Persistent=true

[Install]
WantedBy=timers.target

Enable and inspect it:

sudo systemctl daemon-reload
sudo systemctl enable --now db-backup.timer
systemctl list-timers db-backup.timer
sudo systemctl start db-backup.service
sudo journalctl -u db-backup.service

Schedule upload verification and repository maintenance separately if they can run for a long time. Keep the lock around the complete dump-and-upload transaction when concurrent access could exhaust disk space or bandwidth.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Retention, verification, and alerting

Use layered retention

Retain multiple recovery points rather than only the newest file. A practical policy may include recent daily copies, older weekly copies, and monthly copies for historical incidents. The exact counts should follow your RPO, legal requirements, and storage budget. Apply retention in the remote repository, not only with a local find -delete; otherwise a lost VPS can also erase your history.

Verify each stage

  • Confirm the dump command exits successfully.
  • Confirm the archive exists, is nonempty, and has restrictive permissions.
  • Confirm the upload returns success and the remote snapshot appears.
  • Run repository integrity checks on a schedule.
  • Check free space before creating a dump and alert when thresholds are crossed.
  • Alert on failed dumps, failed uploads, verification errors, and missed timer or cron runs.

Do not treat a snapshot listing, object count, or successful exit code as a restore test. Those checks detect many transport failures, but only an actual import into a disposable database proves that the contents are usable.

Perform a restore drill

At a frequency appropriate to your RPO and change rate, restore a copy to an isolated host or disposable database. Use the same off-site repository and credentials path that production recovery would use, while keeping the restored system disconnected from production users and external side effects.

  1. Choose a dated snapshot and record its timestamp.
  2. Download or mount it on the isolated recovery environment.
  3. For PostgreSQL, create an empty database, restore globals first when required, then load the dump with psql or pg_restore according to the dump format.
  4. For MySQL, create an empty database and import the decompressed SQL with the appropriate client.
  5. Check that expected schemas, tables, indexes, routines, triggers, events, and representative rows exist.
  6. Test application credentials and a read-only application startup against the restored database.
  7. Measure dump retrieval and import time against your RTO.
  8. Destroy the disposable environment and record defects, missing privileges, or undocumented steps.

Restore drills often reveal issues that backup logs cannot: missing roles, absent extensions, expired keys, incompatible client versions, incomplete object exports, or an RTO that was never realistic. Correct the script and run the drill again after material changes to the schema, VPS, database version, or storage backend.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshoot common failures

The dump fails with a permission error

Confirm that the backup identity can connect to the intended database and read every required schema. PostgreSQL global objects require a separate globals export. MySQL routines and events require the corresponding metadata privileges. Test the command as the same operating-system user used by cron or systemd; an interactive shell may be using a different password file or environment.

The upload succeeds but the repository cannot be opened

Check the repository URL, endpoint, region, bucket or path, and credentials available to the scheduler. Ensure the encryption password is present through a protected secret mechanism. Run a repository listing and integrity check from the recovery host, not only from the VPS that created the backup.

Backups overlap or fill the disk

Keep the lock around the operation, reduce compression pressure, and monitor dump duration. Check available space before starting and reserve room for at least one additional archive. Upload promptly and prune only after the remote copy and a verification step succeed.

The restore is incomplete

Compare the dump scope with the production dependency list. PostgreSQL roles, grants, tablespaces, extensions, and WAL are separate concerns from a single database dump. MySQL routines, events, triggers, and nontransactional tables need explicit review. Update the script, document the required order, and repeat the isolated restore.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical decision framework

  • Choose logical dumps when portability, inspectability, and simple operations matter most.
  • Add filesystem or base backups when the dataset makes logical restore time incompatible with your RTO.
  • Use continuous archiving and PITR when recovery to a precise time or a very small RPO is essential and you can operate the additional monitoring and storage.
  • Use Restic when you want an encrypted client with many remote backends and are comfortable scheduling it externally.
  • Use Borg when deduplication, compression, authenticated encryption, and an SSH-accessible repository fit your infrastructure.

Whichever method you choose, the non-negotiable controls are an off-site copy, protected credentials and keys, concurrency protection, retention, failure alerts, and a restore drill that demonstrates the database and application can actually come back.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Borgdatabase backupsDisaster RecoveryLinuxMySQLPostgreSQLResticVPS

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.