Skip to content

How to Back Up MySQL, MariaDB or Postgres

Reviewed in November 2026

Many services and servers require a database whose content needs to be backed up as well. There are different ways to achieve this using Borg or Borgmatic. One method you should avoid is copying the internal data directory of the database, as it’s not safe to copy those files while the database service is running. A better way is to create a compressed dump of the actual data and add that file to the backup. There are multiple ways to do so:

Section titled “Using Borgmatic’s Built-In Database Hook (Recommended)”

If you are already using Borgmatic and have a large database, you can use its built-in database hooks to dump the database content and include it in your backup. The advantage of this technique is that the database dump is read via a named pipe and never written to disk, saving storage space.

To dump all Postgres, MySQL, and MariaDB databases before each backup, add the following snippet to ~/.config/borgmatic/config.yaml, keeping only the hooks for the databases you run:1

postgresql_databases:
- name: all
mysql_databases:
- name: all
mariadb_databases:
- name: all

Most popular distributions include scripts like automysqlbackup2 or autopostgresqlbackup3. Those scripts usually save a daily dump of all databases to a folder like /var/lib/automysqlbackup. By running this script before your backup and including the dump folder in your source directories, you get a timely backup of your database.

For Borgmatic, you can use pre-backup command hooks4 in ~/.config/borgmatic/config.yaml to run the database dump script:

commands:
- before: action
when:
- create
run:
- /usr/sbin/autopostgresqlbackup
  1. Borgmatic: Database Backup Hooks ↩

  2. automysqlbackup ↩

  3. autopostgresqlbackup ↩

  4. Borgmatic: How to add preparation and cleanup steps to backups ↩