How to Automate Encrypted Linux Backups with BorgBackup and Borgmatic
Learn how to configure BorgBackup with Borgmatic to create deduplicated, authenticated, and encrypted automated backups for Linux servers and workstations.
In this article
- Why Choose BorgBackup and Borgmatic?
- Prerequisites
- Step 1: Installing BorgBackup and Borgmatic
- Step 2: Creating and Initializing the Borg Repository
- Step 3: Configuring Borgmatic
- Step 4: Testing the Backup Configuration
- Step 5: Automating Backups with Systemd Timers
- Step 6: Verifying and Restoring Files
- Conclusion
- Frequently Asked Questions
- How does BorgBackup handle deduplication across different servers?
- Is it better to store the encryption key inside the repository or locally?
- What happens if a backup process gets interrupted mid-run?
- How much CPU and memory does BorgBackup consume during runs?
- Can Borgmatic back up database engines like PostgreSQL or MySQL directly?
Standard server backup scripts often rely on basic utilities like rsync or tar. While these tools work for simple setups, they lack built-in deduplication, authenticated encryption, and automated retention management. Over time, storing full or incremental unencrypted tarballs consumes excessive storage space and leaves sensitive system files vulnerable if the backup destination is compromised.
BorgBackup solves these structural challenges by implementing block-level deduplication and client-side AES-256 encryption. However, manually constructing Borg commands with all necessary exclusion rules, passphrase inputs, and remote path arguments can be tedious and prone to human error. That is where Borgmatic comes in. Borgmatic acts as a declarative wrapper for BorgBackup, allowing you to define your backup repositories, excluded files, database integration, and retention schedules inside a clean YAML configuration file.
This guide walks through setting up an automated, encrypted backup pipeline on Linux using BorgBackup and Borgmatic, covering installation, repository initialization, configuration, systemd automation, and restore testing.
Why Choose BorgBackup and Borgmatic?
BorgBackup operates differently than traditional archive utilities. Instead of archiving entire files repeatedly, Borg splits files into variable-length chunks using a rolling hash algorithm. Only unique chunks are encrypted and transmitted to the repository destination.
- Block-Level Deduplication: Identical chunks across different files, directories, or historical snapshots are stored only once, drastically reducing storage consumption.
- Authenticated Client-Side Encryption: All data is encrypted on your machine using AES-256 before transmission. The storage target never receives unencrypted data or passphrase keys.
- Flexible Retention Pruning: Old snapshots can be automatically removed according to custom schedules, such as retaining daily, weekly, and monthly backups.
- Declarative Configuration: Borgmatic replaces complex command-line scripts with a central configuration file, standardizing backup routines across single or multiple machines.
Prerequisites
Before starting the setup, ensure you have the following requirements ready:
- A server or workstation running a modern Linux distribution such as Ubuntu, Debian, Fedora, or Arch Linux.
- Root or administrative sudo privileges on the local system.
- A target storage location, which can be an attached external hard drive, a dedicated NAS dataset, or a remote server accessible over SSH.
- Basic familiarity with terminal command lines and file editing.
Step 1: Installing BorgBackup and Borgmatic
Modern Linux distributions package both BorgBackup and Borgmatic in their official software repositories, making installation quick and straightforward.
On Debian or Ubuntu systems, update your package lists and install both applications using standard system package tools. Run sudo apt update && sudo apt install borgbackup borgmatic in your terminal. On Fedora or RHEL-based systems, run sudo dnf install borgbackup borgmatic.
If your distribution carries an outdated version of Borgmatic, you can alternatively install Borgmatic using pipx, which isolates Python dependencies while making the binary system-accessible. First install pipx via your package manager, then run sudo pipx install borgmatic.
Step 2: Creating and Initializing the Borg Repository
Before Borgmatic can run automated backups, you must initialize an encrypted Borg repository. A repository is the designated directory where Borg stores its chunk database, encryption keys, and snapshot archives.
For local or attached storage backups, target a mount point like /mnt/backups/system-repo. For remote backups over SSH, target a path such as user@remote-backup-server:/var/backups/system-repo.
Initialize the repository using Borg’s initialization command. For a local repository with keyfile-based encryption, execute sudo borg init –encryption=repokey-blake2 /mnt/backups/system-repo. If you are connecting to a remote machine, replace the local path with your SSH location string.
During initialization, you will be prompted to enter a passphrase. Choose a robust, unique passphrase. Borg will encrypt the master repository key with this passphrase. If you lose both the passphrase and the generated keyfile, your backup data will be permanently unrecoverable. Save this passphrase securely in a password manager.
Step 3: Configuring Borgmatic
Borgmatic uses a YAML configuration file to define what files to back up, where to send them, which files to exclude, and how long to keep older archives.
Generate a default Borgmatic configuration directory by running sudo borgmatic config generate. This creates a sample configuration file located at /etc/borgmatic/config.yaml. Open this file using your preferred text editor to customize your backup job.
Inside /etc/borgmatic/config.yaml, you will define four main sections: source directories, repositories, storage settings, and retention rules.
Under the source directories section, specify the folders you want to back up:
- Include paths: /etc, /home, /var/www, and /root.
- Exclude patterns: exclude temporary and cache paths like /home/*/.cache, /var/tmp, and /tmp.
Under the repositories section, list the path to your newly initialized Borg repository. Provide the absolute local path or the full SSH target address you initialized earlier.
Under the retention section, define your pruning strategy. Borgmatic will automatically remove older backup snapshots during maintenance runs according to these parameters:
- Keep daily: 7 (retains one backup per day for the last 7 days).
- Keep weekly: 4 (retains one backup per week for the last 4 weeks).
- Keep monthly: 12 (retains one backup per month for the last 12 months).
Under the storage section, specify the passphrase you created during initialization. To avoid storing plain text passphrases inside the configuration file, you can instruct Borgmatic to read the passphrase from an environment variable or a secure file path using the command option.
Step 4: Testing the Backup Configuration
Before enabling automatic execution, test your configuration manually to confirm that permissions, pathways, and passphrases are correctly set up.
Run a dry run to validate the configuration file structure without writing data: sudo borgmatic –dry-run –verbosity 1. Borgmatic will parse the configuration file, test connection pathways, and output any syntax errors.
Once the dry run completes without errors, initiate an actual manual backup run: sudo borgmatic create –verbosity 1 –stats. Borgmatic will read the target files, compute data chunks, encrypt them locally, write them to the repository destination, and display a statistical summary showing total size, compressed size, and deduplicated storage efficiency.
Step 5: Automating Backups with Systemd Timers
Most Linux installations include systemd service and timer files when installing Borgmatic through standard package managers. Systemd timers are preferred over traditional cron jobs because they provide cleaner logging via journalctl and handle missed schedules gracefully if a system was powered off.
Check if the Borgmatic systemd timer is installed by running sudo systemctl status borgmatic.timer. If the timer file is present, enable and start it with sudo systemctl enable –now borgmatic.timer.
By default, the package timer executes Borgmatic once daily at a randomized time to prevent server load spikes. To inspect when the next backup job will execute, run sudo systemctl list-timers borgmatic.timer.
To verify past automated executions and review execution logs, use journalctl by typing sudo journalctl -u borgmatic.service.
Step 6: Verifying and Restoring Files
A backup system is only as reliable as its restore process. Periodically testing file extraction confirms that data can be quickly recovered during system failures or accidental deletions.
To list all existing backup snapshots stored in the repository, execute sudo borgmatic list. This output displays unique archive names containing hostnames and timestamps.
To extract a specific folder or file from a designated archive back to your local filesystem, use Borgmatic’s extract command: sudo borgmatic extract –archive archive-name –path /etc/nginx. Borgmatic will locate the matching chunks, decrypt them, and place the recovered files into your current directory.
For interactive recovery, you can also mount an entire backup archive as a virtual filesystem using FUSE: sudo borg mount /mnt/backups/system-repo /mnt/restore. You can then browse the contents using standard filesystem commands, copy individual files directly, and unmount the virtual filesystem with sudo umount /mnt/restore when finished.
Conclusion
Combining BorgBackup’s secure deduplication with Borgmatic’s readable configuration management yields a robust, enterprise-grade backup workflow suitable for single Linux servers, homelabs, or cloud infrastructure. Client-side encryption ensures your data remains safe on third-party storage, while automatic pruning keeps storage costs manageable. By validating your setup with regular test restores, you establish a reliable safety net that protects critical files against hardware failure, ransomware, or administrative mistakes.
Frequently Asked Questions
How does BorgBackup handle deduplication across different servers?
Borg performs deduplication within individual repositories. If multiple servers back up into the exact same Borg repository over SSH, Borg can deduplicate identical system files across those distinct machines. If each server backs up to its own separate repository path, deduplication occurs only across the snapshots of that single host.
Is it better to store the encryption key inside the repository or locally?
Using the repokey encryption mode stores the encrypted key inside the repository header itself, protected by your passphrase. This makes repository recovery easier if the client machine experiences total disk loss. However, you should always export a secondary backup of the repository key file using the borg key export command and keep an offline physical copy.
What happens if a backup process gets interrupted mid-run?
Borg creates temporary, uncommitted data checkpoints during backup operations. If a connection drops or power fails mid-run, no existing archives are corrupted. The next time Borgmatic runs, Borg detects incomplete checkpoints and resumes seamlessly or cleans up orphan chunks during standard compaction routines.
How much CPU and memory does BorgBackup consume during runs?
Compute usage depends heavily on your selected compression algorithm (such as zstd or lz4) and chunk calculation size. On low-resource hardware like small virtual machines or older single-board computers, choosing lighter compression settings like lz4 reduces CPU overhead while maintaining strong deduplication benefits.
Can Borgmatic back up database engines like PostgreSQL or MySQL directly?
Yes. Borgmatic features native database hooks in its configuration file. You can configure Borgmatic to automatically perform hot database dumps using tools like mysqldump or pg_dump immediately before taking a file snapshot, ensuring consistent database state without manually writing extra pre-backup scripts.