DebianDebian Based

How To Install Borgmatic on Debian 13

Install Borgmatic on Debian 13

Backing up data is crucial for system administrators and Linux users who value their information. Borgmatic provides an elegant solution for automated, encrypted backups on Debian 13 systems. This comprehensive guide walks through every step of installing and configuring Borgmatic, from initial setup to automated backup scheduling.

Data loss can happen unexpectedly through hardware failures, ransomware attacks, or human error. Borgmatic combines the power of Borg backup with simplified configuration management, offering deduplication, compression, and encryption in one streamlined package. Whether managing a production server or personal workstation, implementing a robust backup strategy protects valuable data and ensures business continuity.

What is Borgmatic?

Borgmatic serves as a configuration-driven wrapper for Borg backup, simplifying the backup process through YAML configuration files. Rather than memorizing complex command-line arguments, users define their backup policies once and let Borgmatic handle the execution.

The tool excels at deduplication, which identifies identical data chunks across different files and stores them only once. This content-defined chunking approach dramatically reduces storage requirements, especially for incremental backups containing mostly unchanged data. Files are split into variable-length chunks, hashed, and compared against existing chunks in the repository. Only new or modified chunks get stored, making subsequent backups incredibly space-efficient.

Borgmatic supports multiple compression algorithms including zstd, lzma, zlib, and lz4. Client-side encryption ensures data security both in transit and at rest, with nobody except the key holder able to access backup contents. The tool integrates seamlessly with systemd timers or cron for automated scheduling, supports database backups through hooks, and provides monitoring integration with services like Healthchecks.io.

Prerequisites and System Requirements

Debian 13 (codenamed “Trixie”) was released in August 2025 and requires modest hardware specifications. The minimum requirements include a 1 GHz processor, 2 GB RAM, and 25 GB of available storage. However, for backup operations, 4 GB RAM or more is recommended to handle compression and encryption efficiently.

Storage planning is essential before implementing Borgmatic. Consider the size of directories being backed up, retention policies, and whether using local or remote repositories. Remote backups require SSH access to the target server and sufficient network bandwidth. Root or sudo privileges are necessary for installation and accessing system directories during backups.

Basic Linux command-line knowledge helps navigate the configuration process. Familiarity with YAML syntax ensures smooth configuration file editing. Understanding file permissions and SSH key authentication becomes important when setting up remote repositories.

Update Your Debian 13 System

Keeping Debian 13 current ensures access to the latest security patches and software versions. Begin by updating the package index to refresh available software lists:

sudo apt update

This command queries configured repositories and downloads information about available packages and updates. Next, upgrade installed packages to their newest versions:

sudo apt upgrade -y

The -y flag automatically confirms the upgrade process without prompting. If the kernel receives updates, consider rebooting the system to load the new kernel version. Check the Debian version to confirm running Debian 13:

cat /etc/debian_version

This should display version 13 or “trixie” indicating Debian 13. System updates create a stable foundation for Borgmatic installation and prevent compatibility issues with outdated dependencies.

Install Borg Backup

Borgmatic requires Borg backup as its underlying engine. Borg handles the actual backup operations while Borgmatic provides the configuration layer and automation. Check whether Borg is already present on the system:

borg --version

If Borg is not installed, install it from Debian’s official repositories:

sudo apt install borgbackup -y

Debian 13 typically includes Borg version 1.2 or higher in its repositories. Verify the installation completed successfully:

which borg

This command displays Borg’s installation path, usually /usr/bin/borg. Test basic Borg functionality by checking its version output again. Borg provides the core deduplication, compression, and encryption features that Borgmatic leverages.

The Borg binary needs to be accessible in the system PATH for Borgmatic to function properly. Remote backups require Borg installation on both the local system and remote backup server. Version compatibility between local and remote Borg installations ensures smooth backup operations across SSH connections.

Install Borgmatic

With Borg in place, proceed to install Borgmatic. Debian 13 includes Borgmatic in its official repositories, simplifying installation:

sudo apt install borgmatic -y

This method installs Borgmatic system-wide and ensures automatic updates through Debian’s package management. Verify successful installation by checking the version:

borgmatic --version

The output should display the installed Borgmatic version number, typically 1.8 or higher for Debian 13. Confirm Borgmatic’s location in the filesystem:

which borgmatic

For users wanting the absolute latest Borgmatic features, pipx offers an alternative installation method. First install pipx:

sudo apt install pipx

Then install Borgmatic through pipx:

sudo pipx install borgmatic

The pipx method installs Borgmatic in an isolated Python environment, preventing conflicts with system packages. However, the Debian repository version receives testing and integration with other Debian components, making it the recommended choice for most users.

Generate Borgmatic Configuration File

Configuration files define Borgmatic’s behavior, specifying what to backup, where to store backups, and how to manage retention. Generate a sample configuration file with all available options:

sudo borgmatic config generate

This creates a comprehensive example configuration at /etc/borgmatic/config.yaml with detailed comments explaining each option. The file includes sections for repositories, source directories, exclusions, retention policies, and advanced features.

Borgmatic supports multiple configuration files for different backup scenarios. Create separate configurations in /etc/borgmatic.d/ for distinct backup jobs. For example, one configuration might handle system files while another focuses on databases.

User-level configurations can be stored in ~/.config/borgmatic/config.yaml for personal backups without requiring root privileges. The tool processes configurations in a specific order, with system-wide settings in /etc/borgmatic/ loaded first.

Open the generated configuration file with a text editor:

sudo nano /etc/borgmatic/config.yaml

Review the structure and commented examples to understand available options. The YAML format uses indentation to define hierarchy, so maintaining proper spacing is crucial.

Configure Borgmatic for Your Needs

Proper configuration transforms Borgmatic into a tailored backup solution. The configuration file contains several critical sections that define backup behavior.

Location Configuration

The source_directories parameter specifies which directories to include in backups:

source_directories:
    - /home
    - /etc
    - /var/www
    - /opt

List each directory on a separate line with proper indentation. Borgmatic supports tilde expansion, allowing ~ to represent the current user’s home directory. Glob patterns enable flexible selection, though specific paths work for most scenarios.

Repository Configuration

Define backup destination repositories where encrypted backup data is stored:

repositories:
    - path: /mnt/backup/borg-repo
      label: local-backup
    - path: ssh://user@example.com/~/backups/borg-repo
      label: remote-backup

Local repositories use absolute filesystem paths, while remote repositories employ SSH syntax. Labels provide human-readable names for easier management when working with multiple repositories. Using both local and remote repositories implements the 3-2-1 backup strategy for enhanced data protection.

Exclude Patterns

Excluding unnecessary files reduces backup size and improves performance:

exclude_patterns:
    - /home/*/.cache
    - '*.tmp'
    - /var/tmp
    - /var/cache
    - /proc
    - /sys
    - /dev
    - /run

Common exclusions include temporary directories, caches, and virtual filesystems that don’t require backing up. Quote patterns containing special characters to ensure proper YAML parsing. Glob patterns like *.log exclude all files with specific extensions across all directories.

Retention Policy

Retention policies determine how long to keep backups before automatic deletion:

keep_daily: 7
keep_weekly: 4
keep_monthly: 6
keep_yearly: 1

This example retains seven daily backups, four weekly backups, six monthly backups, and one yearly backup. Borgmatic automatically prunes older backups exceeding these limits during backup operations. Adjust retention based on storage capacity and recovery requirements.

Encryption Configuration

Encryption protects backup data from unauthorized access:

encryption_passphrase: "your-strong-passphrase-here"

Choose a strong, unique passphrase and store it securely in a password manager. Never commit configuration files containing passphrases to version control systems. Alternative storage methods include environment variables or external passphrase files.

Compression Options

Compression reduces backup storage requirements:

compression: auto,zstd

The auto setting applies compression based on file type, skipping already-compressed formats. Zstd provides excellent compression ratios with good performance. Other options include lz4 for speed, lzma for maximum compression, and zlib for compatibility.

Initialize Your Backup Repository

Repository initialization prepares the storage location for receiving backups. This one-time process creates the repository structure and establishes encryption settings:

sudo borgmatic init --encryption repokey

The repokey encryption mode stores the encryption key within the repository but requires a passphrase for access. This provides strong security while simplifying key management. Alternative modes include keyfile (stores key locally) and none (no encryption).

For configurations with multiple repositories, Borgmatic initializes each one automatically. The initialization process creates the repository structure, generates encryption keys, and prepares internal databases for deduplication tracking.

Export and backup the encryption key immediately after initialization:

borg key export /mnt/backup/borg-repo backup-key.txt

Store this key file securely offline, as losing both the passphrase and key file makes backup data permanently inaccessible. Consider printing the key and storing it in a safe deposit box for maximum security.

Create Your First Backup

With configuration complete and repositories initialized, run the first backup manually to verify everything works correctly:

sudo borgmatic create --verbosity 1 --list --stats

The --verbosity 1 flag provides detailed progress information during the backup. The --list option displays each file as Borgmatic processes it. The --stats flag shows backup statistics including original size, deduplicated size, and compression ratio.

The first backup takes longer than subsequent backups because every file must be chunked, compressed, and stored. Watch for errors indicating permission problems, missing directories, or configuration issues. Subsequent incremental backups complete much faster due to deduplication identifying unchanged data.

Verify backup success by listing available archives:

sudo borgmatic list

This displays all backup archives in the repository with their timestamps and names. Archive names follow a pattern including hostname and timestamp for easy identification.

Automate Backups with Systemd

Systemd timers provide reliable backup scheduling on Debian 13 systems. Borgmatic includes systemd service and timer units that integrate seamlessly with the system.

Check if systemd units are already installed:

systemctl list-unit-files | grep borgmatic

Most Borgmatic installations include borgmatic.service and borgmatic.timer automatically. If not present, create them manually in /etc/systemd/system/.

Enable the systemd timer to start automatically at boot:

sudo systemctl enable borgmatic.timer

Start the timer immediately without waiting for the next boot:

sudo systemctl start borgmatic.timer

Check the timer status and next scheduled run time:

sudo systemctl status borgmatic.timer

View all active timers to confirm Borgmatic appears in the list:

systemctl list-timers

The default timer runs Borgmatic daily, typically during off-peak hours. Customize the schedule by editing /etc/systemd/system/borgmatic.timer and modifying the OnCalendar directive. For example, OnCalendar=daily runs once per day, while OnCalendar=*-*-* 02:00:00 runs at 2:00 AM.

After modifying systemd unit files, reload the systemd daemon:

sudo systemctl daemon-reload

For users preferring cron-based scheduling, add an entry to the root crontab:

sudo crontab -e

Add a line scheduling Borgmatic to run at 2:00 AM daily:

0 2 * * * /usr/bin/borgmatic --syslog-verbosity 1

The --syslog-verbosity flag sends output to the system log for monitoring. Redirect output to a log file if needed for review and troubleshooting.

Testing and Verification

Regular testing ensures backups function correctly and data can be restored when needed. Run consistency checks to verify repository integrity:

sudo borgmatic check --progress

Consistency checks examine repository structure, verify chunk integrity, and detect corruption. Schedule checks weekly or monthly depending on backup frequency and paranoia level.

List all available backup archives to see what’s stored:

sudo borgmatic list --json

The --json flag outputs structured data suitable for programmatic processing. Without it, the command displays human-readable archive information including creation dates and sizes.

Test restoration before needing it in an emergency. Extract a specific file to verify backup contents:

sudo borgmatic extract --archive latest --path /etc/hostname --destination /tmp/restore-test

This extracts the /etc/hostname file from the latest archive to /tmp/restore-test for verification. Compare the restored file against the original to confirm accuracy. Perform quarterly full restore tests to a separate system or virtual machine to validate entire backup sets.

Monitor backup size and growth trends:

sudo borgmatic info

This command displays repository statistics including total size, unique data, and compression ratios. Tracking growth helps plan storage capacity and identify unusual changes indicating configuration problems.

Restore Files from Backup

Restoration retrieves data from backup archives when files are lost or corrupted. Borgmatic provides flexible restore options for various scenarios.

Extract a specific file or directory from the latest backup:

sudo borgmatic extract --archive latest --path /home/user/important-document.pdf

This restores the file to its original location. Add --destination /tmp/restore to extract to an alternate location:

sudo borgmatic extract --archive latest --path /home/user/important-document.pdf --destination /tmp/restore

Restore multiple files matching a pattern:

sudo borgmatic extract --archive latest --path '/home/user/*.conf'

Quote patterns to prevent shell expansion before Borgmatic processes them. Browse archive contents before restoration by listing files:

sudo borgmatic list --archive latest --paths

For recovering files from a specific date, list archives to find the appropriate backup:

sudo borgmatic list

Then extract using the specific archive name:

sudo borgmatic extract --archive hostname-2025-10-01T02:00:00 --path /home/user/deleted-file

Mount archives as FUSE filesystems for convenient browsing:

sudo borg mount /mnt/backup/borg-repo /mnt/restore-mount

Navigate the mounted directory structure normally, copying needed files out before unmounting. This approach works well when the exact file path is unknown or multiple files need reviewing.

Troubleshooting Common Issues

Installation Problems

Package dependency conflicts occasionally prevent Borgmatic installation. Resolve broken dependencies with:

sudo apt --fix-broken install

This command identifies and corrects dependency issues automatically. Update the package cache if repositories seem out of date:

sudo apt update && sudo apt upgrade

Configuration Errors

YAML syntax errors cause Borgmatic to fail with parsing errors. Validate configuration syntax:

sudo borgmatic config validate

This identifies formatting problems and invalid parameter values. Common mistakes include incorrect indentation, missing colons, or improperly quoted strings. Pay special attention to list formatting and ensure consistent spacing throughout the file.

Backup Failures

Permission denied errors indicate insufficient privileges for accessing files or directories. Ensure Borgmatic runs with appropriate permissions, typically as root for system-wide backups. Check file ownership and permissions on source directories.

SSH connection failures affect remote backups. Verify SSH access works independently:

ssh user@example.com

Confirm SSH keys are properly configured and the remote Borg installation is accessible. Test the remote repository path for correct permissions and available space.

Repository Issues

“Repository already exists” errors occur when attempting to initialize an existing repository. Skip initialization or create a new repository path instead. Lock timeout errors happen when previous backup operations didn’t complete cleanly:

sudo borg break-lock /mnt/backup/borg-repo

Use this command cautiously and only when certain no backup processes are running. Breaking locks during active backups causes repository corruption.

Repository corruption requires repair operations:

sudo borg check --repair /mnt/backup/borg-repo

This command attempts to fix detected issues, though severe corruption may result in data loss. Regular consistency checks and multiple backup repositories minimize risk.

Performance Problems

Slow backup speeds often result from aggressive compression settings. Reduce compression levels or switch to faster algorithms like lz4. Network bandwidth constraints affect remote backups—consider compression trade-offs between CPU usage and transfer time.

Memory constraints cause backups to slow or fail on systems with limited RAM. Increase available memory or reduce checkpoint intervals in the configuration. Large files may require special handling through chunker settings tuning.

Best Practices and Security Tips

Strong encryption passphrases protect backup data from unauthorized access. Use password managers to generate and store complex passphrases securely. Never embed passphrases directly in version-controlled configuration files—use environment variables or separate passphrase files instead.

Implement the 3-2-1 backup strategy: maintain three copies of data, stored on two different media types, with one copy offsite. Configure Borgmatic with both local and remote repositories to achieve this redundancy.

Regular testing validates backup integrity and restore procedures. Schedule quarterly restore tests to ensure recovery processes work when needed. Document restoration procedures and keep instructions accessible outside the backup system.

Monitor backup operations through integration with external services like Healthchecks.io or Cronitor. Configure webhook URLs in Borgmatic configuration to receive notifications on backup success or failure:

before_backup:
    - echo "Starting backup"
    - curl -fsS -m 10 --retry 5 -o /dev/null https://hc-ping.com/your-uuid/start

after_backup:
    - echo "Backup completed"
    - curl -fsS -m 10 --retry 5 -o /dev/null https://hc-ping.com/your-uuid

This provides immediate alerts when backups fail to run or encounter errors.

Protect configuration files with appropriate permissions, preventing unauthorized users from viewing encryption passphrases or backup locations:

sudo chmod 600 /etc/borgmatic/config.yaml

Regular maintenance keeps the backup system healthy. Update Borgmatic and Borg periodically to receive security patches and feature improvements:

sudo apt update && sudo apt upgrade borgmatic borgbackup

Review and update retention policies as storage requirements change. Adjust exclusion patterns to accommodate new directories or file types. Prune old archives manually if needed to reclaim storage space immediately:

sudo borgmatic prune

Append-only mode prevents backup deletion by compromised systems, protecting against ransomware and malicious actors:

repositories:
    - path: ssh://backup@example.com/~/backups/borg-repo
      label: remote-backup
ssh_command: ssh -o ServerAliveInterval=120 -o ServerAliveCountMax=3

Configure the remote repository with append-only permissions, requiring manual intervention to delete archives.

Advanced Configuration Options

Database backups require special handling beyond filesystem copying. Borgmatic supports database backup hooks that dump database contents before backup operations:

postgresql_databases:
    - name: mydb
      hostname: localhost
      username: postgres

mysql_databases:
    - name: wordpress
      hostname: localhost
      username: backup_user
      password: secure_password

These hooks automatically dump databases to temporary files, include them in backups, and clean up afterward. This ensures consistent database backups without manual export procedures.

Pre and post-backup hooks enable custom actions around backup operations:

before_backup:
    - echo "Starting backup at $(date)" >> /var/log/borgmatic-custom.log
    - /usr/local/bin/prepare-backup.sh

after_backup:
    - echo "Backup completed at $(date)" >> /var/log/borgmatic-custom.log
    - /usr/local/bin/cleanup-backup.sh

Hooks support scripts for custom logic like snapshotting filesystems, mounting network shares, or notifying external systems.

Cloud storage backends extend backup options beyond local and SSH repositories. Services like rsync.net, BorgBase, and AWS S3 (via rclone) provide offsite storage with varying cost structures. Configure SSH-accessible cloud storage as regular remote repositories in Borgmatic configuration.

Multiple configuration files enable different backup schedules and policies for distinct data types. Create separate configurations in /etc/borgmatic.d/ for hourly, daily, and weekly backups with appropriate retention policies. Each configuration runs independently, allowing fine-grained control over backup behavior.

Congratulations! You have successfully installed Borgmatic. Thanks for using this tutorial for installing the Borgmatic backup program on your Debian 13 “Trixie” Linux system. For additional help or useful information, we recommend you check the official Borgmatic website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is a dedicated and highly skilled Linux Systems Administrator with over a decade of progressive experience in designing, deploying, and maintaining enterprise-grade Linux infrastructure. His professional journey began in the telecommunications industry, where early exposure to Unix-based operating systems ignited a deep and enduring passion for open-source technologies and server administration.​ Throughout his career, r00t has demonstrated exceptional proficiency in managing large-scale Linux environments, overseeing more than 300 servers across development, staging, and production platforms while consistently achieving 99.9% system uptime. He holds advanced competencies in Red Hat Enterprise Linux (RHEL), Debian, and Ubuntu distributions, complemented by hands-on expertise in automation tools such as Ansible, Terraform, Bash scripting, and Python.
Back to top button