Sub topic 14
Backing Up the Database
This chapter assumes that you can use the Linux command line, run SQL, and manage PostgreSQL or MySQL services with systemctl. It also assumes that you know where the database server stores its data and that you can create a temporary database for testing.
A backup is a copy of database data that you can use after accidental deletion, corruption, hardware failure, or an unsafe deployment. A backup is useful only if it is complete, protected, and restorable.
Logical and physical backups
A logical backup contains SQL-level objects such as tables, rows, indexes, users, and routines. PostgreSQL uses pg_dump; MySQL commonly uses mysqldump. Logical backups are portable and convenient for moving one database, but large databases can take longer to restore.
A physical backup copies database files or storage snapshots. It is usually faster for large systems and can support complete server recovery. It depends more closely on the database version, storage layout, and backup tooling.
| Backup type | Best use | Main limitation |
|---|---|---|
| Logical | Moving one database or recovering selected objects | Restore can be slow |
| Physical | Full recovery of a large server | Tied to server layout and version |
A backup stored on the same disk as the database does not protect against disk failure. Copy backups to separate storage, restrict access to them, and encrypt them when they leave the server.
Create a logical backup
For PostgreSQL, the custom format works well with pg_restore. Run the command as a database role that can read the required objects.
pg_dump -Fc -f appdb.dump appdbFor MySQL, --single-transaction creates a consistent snapshot for InnoDB tables without locking normal reads and writes for the entire dump.
mysqldump --single-transaction --routines --events appdb > appdb.sqlThese commands do not automatically provide a complete disaster-recovery plan. Include backup scheduling, retention, monitoring, and an off-host copy. Decide how much data the organization can lose. This limit is the recovery point objective, or RPO. Decide how quickly service must return. This limit is the recovery time objective, or RTO.
Test a restore
Restore into a separate scratch database. Never test by overwriting the production database.
# PostgreSQL
createdb appdb_restore_test
pg_restore --dbname=appdb_restore_test appdb.dump
# MySQL
mysql -e 'CREATE DATABASE appdb_restore_test'
mysql appdb_restore_test < appdb.sqlAfter restoring, check that expected tables exist and that representative queries return the expected data. Record the restore duration and any errors. Automate these checks when possible.
Exercise
Why should a logical backup be restored into a scratch database during testing?
Show answer
A scratch database verifies that the backup is usable without risking changes to production data.