BorgBackup for Linux Servers

Khimananda Oli 8 min read Virtualization
BorgBackup for Linux Servers

By Khimananda Oli | Last reviewed: August 2026

Data loss is rarely a dramatic catastrophe; usually, it is a silent corruption or a misconfigured script that goes unnoticed until recovery fails. When managing infrastructure across Nepal’s variable network conditions or global cloud regions, you need a backup solution that respects bandwidth constraints and storage costs. BorgBackup for Linux Servers solves this by combining deduplication, compression, and authenticated encryption into a single efficient workflow, making it the industry standard for modern systems administration.

How does BorgBackup for Linux Servers handle deduplication and encryption?

Unlike traditional tools like tar or rsync that copy entire files during every run, BorgBackup operates at the chunk level. It splits files into variable-size blocks using a rolling hash algorithm. Before writing any data to disk, Borg calculates a cryptographic hash of each chunk. If that hash already exists in the repository, the chunk is simply referenced rather than stored again. This means your second backup of a 100GB database might only consume 50MB of additional storage if only a few rows changed.

Source FilesChunker & HasherSHA-256Dedup CheckCompress + EncryptBorg RepositoryUnique Chunks OnlyEncrypted MetadataIndex + Manifest
BorgBackup deduplication pipeline: source files are chunked, hashed, deduplicated, encrypted, and stored as unique blocks in the repository.

Encryption is not an afterthought in Borg; it is foundational. Every chunk is encrypted before leaving memory using AES-CTR-256, and HMAC-SHA256 provides authentication. You can choose between repokey (where the encrypted key lives in the repository config) or keyfile (where the key stays on your client machine). For most Ubuntu server backup strategies, repokey-blake2 offers the best balance of security and performance on modern CPUs. Always remember: if you lose both the repository and your key, the data is gone forever. Export your key immediately after initialization.

How do you install and initialize a BorgBackup repository?

Getting started requires installing the package and creating a secure repository. On Ubuntu 24.04 LTS or Debian 12+, the distribution packages are current and well-maintained.

sudo apt update
sudo apt install borgbackup

# Initialize a new encrypted repository with BLAKE2 hashing
borg init --encryption=repokey-blake2 /mnt/backup/borg-repo

# CRITICAL: Export your encryption key immediately
borg key export /mnt/backup/borg-repo ~/borg-key-backup.txt

The initialization step creates the repository structure and generates your master encryption key. The --encryption=repokey-blake2 flag stores the key inside the repository (encrypted with your passphrase) and uses BLAKE2b for faster checksums than SHA-256. Store the exported key file in a separate location—ideally offline or in a password manager. Without it, even knowing the passphrase won't help if the repository's internal key metadata becomes corrupted.

Setting up SSH-based remote repositories

For offsite backups, Borg works natively over SSH without requiring special server software. The remote host only needs the borg binary installed. Use an SSH key with restricted permissions for automation:

# Create a dedicated backup user on the remote server
ssh backup@remote-host "borg init --encryption=repokey-blake2 /srv/borg/myserver"

# Test connectivity and repository access
borg info ssh://backup@remote-host/srv/borg/myserver

This approach integrates cleanly with existing SSH hardening practices. Restrict the backup user's shell and use authorized_keys command restrictions to limit what the connecting key can do, preventing lateral movement if the backup client is compromised.

What are the essential BorgBackup commands for daily operations?

Once initialized, three commands form your operational core: create, prune, and compact. Understanding their flags prevents common mistakes that waste storage or leave gaps in coverage.

  • Create: Captures a snapshot with deduplication and compression.
  • Prune: Enforces retention policies by deleting old archives.
  • Compact: Reclaims space freed by pruning (required since Borg 2.x).
  • List/Extract: Browses and restores individual files or full archives.
# Create a compressed, deduplicated archive with progress output
borg create --progress --compression=zstd,3 \
  --exclude-caches \
  --exclude '*.tmp' \
  /mnt/backup/borg-repo::'{hostname}-{now:%Y-%m-%d_%H%M}' \
  /etc /var/www /home /opt/app-data

# Apply retention policy: keep last 7 daily, 4 weekly, 6 monthly
borg prune --list --glob-archives='{hostname}-*' \
  --keep-daily=7 --keep-weekly=4 --keep-monthly=6 \
  /mnt/backup/borg-repo

# Reclaim freed space (mandatory after prune in Borg 2.x)
borg compact --progress /mnt/backup/borg-repo

A common mistake is forgetting borg compact. In older versions, space was reclaimed automatically during prune. Since Borg 2.x, compaction is explicit. Without it, your repository grows indefinitely even though old archives are deleted. Schedule compaction right after pruning in your automation scripts.

borg createDeduplicate + CompressNew Archive Created✓ Incremental Snapshotborg pruneApply Retention PolicyDelete Old Archives⚠ Space Not Yet Freedborg compactReclaim Freed BlocksShrink Repository✓ Storage Optimized
Daily BorgBackup workflow: create captures data, prune enforces retention, and compact reclaims storage space.

How do you automate BorgBackup with systemd timers and borgmatic?

Running Borg manually is fine for testing, but production systems demand automation. Two approaches dominate: raw systemd timers or borgmatic, a wrapper that simplifies configuration. For teams managing multiple servers, borgmatic reduces boilerplate significantly. However, understanding the underlying systemd integration remains valuable for debugging and minimal setups.

Using borgmatic for declarative configuration

Borgmatic replaces complex shell scripts with a YAML config file. Install it via pip or apt, then generate a base configuration:

sudo apt install borgmatic
generate-borgmatic-config -d /etc/borgmatic/config.yaml

Edit /etc/borgmatic/config.yaml to define sources, repositories, retention, and hooks. Borgmatic handles locking, error reporting, and pre/post-backup commands (like database dumps) declaratively. This aligns well with idempotent infrastructure principles, making your backup configuration version-controllable and auditable.

Systemd timer alternative for minimal setups

If you prefer avoiding extra dependencies, systemd timers provide native scheduling with dependency management and logging:

# /etc/systemd/system/borg-backup.service
[Unit]
Description=Borg Backup Job
RequiresMountsFor=/mnt/backup

[Service]
Type=oneshot
ExecStart=/usr/bin/borg create --compression=zstd,3 /mnt/backup/repo::{hostname}-{now} /etc /var/www
ExecStartPost=/usr/bin/borg prune --keep-daily=7 --keep-weekly=4 /mnt/backup/repo
ExecStartPost=/usr/bin/borg compact /mnt/backup/repo

Pair this with a corresponding .timer unit set to OnCalendar=*-*-* 02:00:00. Systemd ensures the backup mount is available before execution and captures all output in the journal. This method avoids cron's limitations around environment variables and missed runs during downtime.

BorgBackup vs Restic vs Rsync: Which backup tool should you choose?

Choosing the right tool depends on your specific constraints. While Borg excels in many scenarios, alternatives have distinct strengths worth evaluating honestly.

FeatureBorgBackupResticRsync
DeduplicationYes (chunk-level)Yes (chunk-level)No (file-level only)
EncryptionBuilt-in (AES-256)Built-in (AES-256)None (transport only)
Cloud Backend SupportLimited (via rclone)Native (S3, B2, GCS)Via SSH/mount
Performance (Local)ExcellentGoodFastest (no overhead)
Maturity & Audit TrailHigh (since 2015)High (since 2015)Very High (since 1996)
Best ForLinux servers, VPS, complianceMulti-cloud, heterogeneous OSSimple mirroring, no history

In practice, Borg wins for dedicated Linux server environments where performance and storage efficiency matter most. Its mature ecosystem, excellent documentation, and proven reliability make it the default choice for security-conscious deployments. Choose Restic when backing up directly to S3-compatible object storage across mixed operating systems. Stick with rsync only when you need simple directory mirroring without version history or encryption.

BorgBackup★ Best for Linux Servers✓ Fastest Local Performance✓ Mature Ecosystem✓ Compliance Ready△ Cloud Needs rcloneResticBest for Multi-Cloud✓ Native S3/B2/GCS✓ Cross-Platform△ Slower Locally△ Younger ToolingRsyncSimple Mirroring Only✗ No Deduplication✗ No Encryption✗ No Version History✓ Fastest Raw Copy
Tool comparison: BorgBackup leads for Linux servers, Restic excels in multi-cloud, rsync suits simple mirroring without history.

Implementing BorgBackup for Linux Servers in Production

Deploying BorgBackup effectively requires more than just running commands—it demands integration with your broader operational discipline. Start by documenting your encryption key storage procedure and testing restores quarterly. A backup you cannot restore is merely a hope. Integrate backup health checks into your monitoring stack alongside the metrics covered in the four golden signals of monitoring; track repository size growth, last successful backup timestamp, and prune duration as first-class SLIs.

For teams handling sensitive data or preparing for SOC 2 audits, Borg's authenticated encryption provides verifiable protection at rest. Combine it with offsite replication to meet compliance requirements without sacrificing performance. Remember that automation without observability creates silent failures. Wire borgmatic's JSON output or systemd journal logs into your centralized logging platform so backup issues surface before they become disasters.

If you are designing a backup strategy for critical infrastructure and need guidance tailored to your environment, reach out to discuss your specific requirements. Getting the foundation right prevents costly rework later.

Frequently Asked Questions

BorgBackup is a deduplicating backup program for Linux that stores data efficiently using content-defined chunking. It supports encryption, compression, and remote repositories over SSH, making it ideal for server backups where storage space and bandwidth are limited.

Run sudo apt update followed by sudo apt install borgbackup to get the latest stable version from official repositories. Verify installation with borg --version to confirm you have version 1.4 or newer before initializing your first repository.

Yes, completely free.

Borg uses a single-file repository format with better deduplication ratios for similar files, while Restic uses multiple pack files. Borg typically achieves faster backup speeds on local storage but Restic offers broader cloud backend support without additional tools.

BorgBackup uses AES-CTR-256 encryption with HMAC-SHA256 authentication when initialized with repokey or keyfile modes. The encryption key is stored separately from the repository in repokey mode or locally in keyfile mode for enhanced security isolation.

Run borg init --encryption=repokey /path/to/repo and set a strong passphrase when prompted. This creates an encrypted repository where the key is stored inside the repository itself, protected by your passphrase for secure server backups.

No, never back up live databases directly. Use pg_dump or mysqldump to create consistent snapshots first, then back up those dump files with Borg. Backing up active database files risks corruption and unrecoverable restores during recovery operations.

Use lz4 for fast backups with moderate compression or zstd,3 for balanced performance. Avoid zlib or lzma on production servers unless testing confirms acceptable speed trade-offs, as they significantly increase CPU usage during backup windows.

Create a service unit running borg create and a corresponding timer unit with OnCalendar=daily. Enable both with systemctl enable --now borg-backup.timer to schedule automated backups without cron dependency issues or missed runs after reboots.

Run borg check --repair to verify and fix repository integrity. Always maintain offline copies of critical repositories since some corruption types are unrecoverable. Regular verification prevents discovering failures only during emergency restoration scenarios.

Savings vary significantly.

Yes, run borg mount /path/to/repo::archive-name /mnt/point to access backup contents as a read-only filesystem. Install fuse3 package first. Unmount with fusermount -u when finished browsing to release system resources properly.

Use borg extract /path/to/repo::archive-name path/to/file to restore individual files or directories. Specify exact paths from borg list output. Extracted files retain original permissions and timestamps unless overridden with extraction options.

Yes, always.

Use borg prune --keep-daily=7 --keep-weekly=4 --keep-monthly=6 to balance recovery points with storage costs. Adjust based on compliance requirements and change frequency. Always test prune commands with --dry-run before applying to production repositories.