Sub topic 14
Backing up the database
This chapter covers logical and physical backups, how to run them on a schedule, and what to do with the output. It assumes you can run sudo, can write basic shell scripts, have a working PostgreSQL or MySQL server from the earlier chapters, and know what a systemd unit is. Verifying that a backup restores is the next chapter's subject. Here we focus on producing backups that are consistent, protected and automated.
Why a backup is not a copy of the data directory
Copying /var/lib/postgresql or /var/lib/mysql while the server runs usually gives you a corrupt copy. The server holds changes in memory and writes data files and logs at different moments. A file-level copy can capture pages from different points in time. A backup has to be taken through the database engine, or from a filesystem snapshot that the engine can recover from.
There are two families of backup:
| Row | Logical backup | Physical backup |
|---|---|---|
| Contents | SQL statements or a dump format that recreates objects and rows | Copy of the data files plus the logs needed to make them consistent |
| Tools | `pg_dump`, `pg_dumpall`, `mysqldump` | `pg_basebackup`, WAL archiving, Percona XtraBackup, filesystem snapshots |
| Restore scope | One table, one database, or the whole server | Whole server (or whole cluster) |
| Cross-version restore | Usually works, which makes it useful for upgrades | Same major version and architecture only |
| Speed on large data | Slow to take and slow to restore | Fast, close to disk speed |
| Point-in-time recovery | No | Yes, with archived logs |
Logical backups with PostgreSQL
pg_dump backs up one database. It runs inside a single transaction snapshot, so the dump is consistent even while applications write to the database. Writers are not blocked.
sudo -u postgres pg_dump -Fc -f /var/backups/db/appdb.dump appdb-Fc selects the custom format. It is compressed, and pg_restore can select individual objects from it. For large databases, the directory format dumps tables in parallel:
sudo -u postgres pg_dump -Fd -j 4 -f /var/backups/db/appdb.dir appdbpg_dump does not include roles or tablespace definitions, because those belong to the whole cluster. Back them up separately, or a restore on a new server will fail with "role does not exist" errors:
sudo -u postgres pg_dumpall --globals-only > /var/backups/db/globals.sqlThe globals file contains password hashes, so protect it like the dump itself.
Logical backups with MySQL
mysqldump writes SQL text. The --single-transaction option takes a consistent snapshot of InnoDB tables without locking them. It does not give a consistent view of MyISAM tables, so a server that still has them needs a different approach.
mysqldump --single-transaction --routines --events --triggers appdb \
| gzip > /var/backups/db/appdb.sql.gzStored routines and events are skipped by default, which is why the example names them. Triggers are included by default, and naming them is harmless. On MySQL 8.0.26 and later, add --source-data=2 to record the binary log position as a comment in the dump. Older versions call this option --master-data=2. You need that position if you later want to replay the binary log on top of the dump.
Authenticating the backup job
An unattended job needs credentials that do not appear on the command line, where other users can see them in the process list.
- PostgreSQL: run the job as the
postgresoperating system user, which uses peer authentication with no password. For a less privileged job, create a role that is a member ofpg_read_all_data(PostgreSQL 14 and later) and store its password in~/.pgpasswith mode0600. - MySQL: put the account in a
[client]section of~/.my.cnfwith mode0600. Grant it only what the dump needs, typicallySELECT,SHOW VIEW,TRIGGERandEVENTon the target database.
Physical backups
A physical backup copies the data files while the server runs and records the log position needed to make the copy consistent.
For PostgreSQL, pg_basebackup does this over a replication connection. The connecting role needs the REPLICATION attribute, and pg_hba.conf needs a matching replication entry:
sudo -u postgres pg_basebackup -D /var/backups/db/base -Ft -z -X stream -P-X stream includes the write-ahead log (WAL) generated during the copy, so the backup is self-contained. If you also archive WAL continuously with archive_mode and archive_command, you can restore the base backup and replay WAL to any moment you choose. This is point-in-time recovery.
For MySQL, the usual physical tool is Percona XtraBackup (or MySQL Enterprise Backup). Alternatively, take an LVM or ZFS snapshot of the data volume. The snapshot is crash-consistent, and InnoDB recovers from it at startup, as if the server had lost power. Keep the binary logs on the same snapshot or archive them separately to allow point-in-time recovery.
Scheduling with a systemd timer
A timer gives you logging through the journal and systemctl visibility, which cron does not. The script below dumps one database, writes it with restrictive permissions, and removes old files.
#!/usr/bin/env bash
# /usr/local/sbin/backup-appdb.sh
set -euo pipefail
umask 077
dest=/var/backups/db
stamp=$(date +%Y%m%d-%H%M%S)
tmp="$dest/appdb-$stamp.dump.partial"
pg_dump -Fc -f "$tmp" appdb
mv "$tmp" "$dest/appdb-$stamp.dump"
find "$dest" -name 'appdb-*.dump' -mtime +14 -deleteWriting to a .partial name and renaming at the end means a half-written file is never mistaken for a good backup. set -euo pipefail makes the script fail on any error, so systemd records the run as failed.
# /etc/systemd/system/backup-appdb.service
[Unit]
Description=Dump appdb
[Service]
Type=oneshot
User=postgres
ExecStart=/usr/local/sbin/backup-appdb.sh# /etc/systemd/system/backup-appdb.timer
[Unit]
Description=Nightly appdb dump
[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true
[Install]
WantedBy=timers.targetCreate the directory with sudo install -d -o postgres -m 700 /var/backups/db, then run sudo systemctl enable --now backup-appdb.timer. Persistent=true runs a missed job at the next boot. Check results with systemctl list-timers and journalctl -u backup-appdb.service.
Protecting the backup
- Store a copy off the host. A backup on the same disk is lost with the disk. Copy files to another machine or object storage after each run.
- Restrict access. Dumps contain every row you can read. Keep them in a directory with mode
0700, and encrypt them (for example withgpgorage) before they leave the host. - Define retention. Decide how many daily, weekly and monthly copies to keep. The
find -mtimeline above is the simplest policy. - Monitor the job. A timer that has silently failed for three weeks is the common way to find out you have no backups. Alert on a failed unit or on a newest backup file older than 25 hours.
Common errors
pg_dump: error: connection to server ... failed: FATAL: Peer authentication failed. The job runs as the wrong operating system user. Run it aspostgres, or use a role with a password and.pgpass.mysqldump: Got error: 1044: Access denied ... when using LOCK TABLES. Use--single-transactionfor InnoDB, or grantLOCK TABLES.- A zero-byte or truncated dump. In a pipeline, the shell reports only the last command's status unless
pipefailis set. The script above sets it. - A restore fails on missing roles. You backed up the database but not the globals from
pg_dumpall --globals-only. - A dump that "works" but is unusable. Only a restore proves otherwise, which is the next chapter.
Exercise
A MySQL server holds only InnoDB tables and must stay available during backups. Which mysqldump option gives a consistent dump without locking the tables, and what two object types does the dump omit unless you ask for them?
Show answer
--single-transaction takes the dump inside one consistent snapshot without blocking writers. Stored routines and events are omitted unless you add --routines and --events.
Exercise
Your nightly pg_dump job succeeds, but after rebuilding the server from it, applications cannot log in. What did the backup miss, and which command captures it?
Show answer
It missed the cluster-wide roles, because pg_dump covers only one database. Run pg_dumpall --globals-only and restore that file before restoring the database.