Automating Secure VPS Backups: A Complete Guide to Borgmatic and Cloudflare R2
Introduction: The Imperative of Automated, Encrypted Backups
In the modern digital landscape, data is arguably an organization’s most valuable asset. For businesses relying on Virtual Private Servers (VPS) to host critical applications, databases, and customer records, a robust backup strategy is not a luxury—it is a fundamental operational necessity. Hardware failures, cyberattacks, accidental deletions, and software corruption pose continuous threats to business continuity.
To mitigate these risks effectively, enterprise data protection must adhere to the 3-2-1 backup strategy: maintain at least three copies of your data, store them on two different types of media, and keep at least one copy off-site. Furthermore, in an era of stringent compliance regulations (such as GDPR and HIPAA) and sophisticated ransomware, backups must be encrypted at rest and in transit.
This comprehensive guide demonstrates how to establish an automated, highly secure, and cost-effective backup pipeline for your VPS. By leveraging Borgmatic—a powerful, configuration-driven wrapper for the BorgBackup deduplicating framework—and pairing it with Cloudflare R2—an S3-compatible, zero-egress-fee object storage solution—you can achieve enterprise-grade data resilience with minimal overhead.
Why Borgmatic and Cloudflare R2?
Before diving into the technical implementation, it is essential to understand why this specific toolchain represents an optimal solution for systems administrators and business leaders alike.
- Borgmatic (BorgBackup): Unlike traditional backup tools that copy entire files repeatedly, Borg uses authenticated, client-side encryption and secure deduplication. It splits files into variable-length chunks, ensuring that only modified blocks are stored. This drastically reduces repository size, shortens backup windows, and minimizes bandwidth utilization.
- Cloudflare R2: Traditional cloud storage providers often charge unpredictable data egress fees when you need to restore your data. Cloudflare R2 eliminates egress fees entirely, providing predictable cloud storage costs. Operating on Cloudflare’s global network, it ensures high availability, durability, and low latency.
Security Note: Because Borgmatic encrypts data locally before transmitting it, Cloudflare R2 never possesses the keys to decrypt your files. This establishes a strict zero-trust storage architecture.
Prerequisites and Environment Setup
To follow this guide, ensure your environment meets the following baseline requirements:
- A VPS running a modern Linux distribution (e.g., Ubuntu 22.04 LTS or Debian 12).
- Root or
sudoadministrative privileges on the server. - A verified Cloudflare account with R2 storage enabled.
Let us begin by preparing the local environment and installing the required software packages.
Step 1: Installing BorgBackup and Borgmatic
First, update your system package index and install BorgBackup along with its dependencies. We will install Borgmatic via pip to ensure we have access to the latest configuration schemas and features.
sudo apt update && sudo apt install -y borgbackup python3-pip python3-venv
# Create a dedicated virtual environment for Borgmatic to avoid system package conflicts
sudo python3 -m venv /opt/borgmatic
sudo /opt/borgmatic/bin/pip install --upgrade pip setuptools wheel
sudo /opt/borgmatic/bin/pip install borgmatic
# Symlink the binary for global system availability
sudo ln -s /opt/borgmatic/bin/borgmatic /usr/local/bin/borgmatic
Verify the installation by checking the version:
borgmatic --version
Provisioning Cloudflare R2 Storage
Next, we must configure our remote storage bucket within the Cloudflare dashboard and obtain the necessary API credentials to allow our VPS to securely authenticate via the S3 protocol.
Step 2: Creating the R2 Bucket and API Credentials
- Log in to your Cloudflare Dashboard and navigate to the R2 section in the sidebar.
- Click Create bucket. Name your bucket descriptively (e.g.,
vps-enterprise-backups) and click Create bucket to finalize. - Return to the main R2 page and click on Manage R2 API Tokens on the right-hand side.
- Click Create API token. Configure the token permissions carefully:
- Token name:
Borgmatic VPS Backup Token - Permissions: Edit (Allows read and write operations required for backups and pruning)
- Bucket scoping: Specific buckets (Select the bucket created in step 2)
- Token name:
- Click Create Token.
Important: Copy the following credentials immediately to a secure password manager. They will not be displayed again:
- Access Key ID
- Secret Access Key
- Jurisdiction-specific Endpoint (e.g.,
https://).r2.cloudflarestorage.com
Configuring R2 Repository via rclone Integration
Because BorgBackup natively targets local directories or SSH endpoints, the most robust method for sending Borg archives to object storage is utilizing Borgmatic’s native hook architecture or syncing a local cache directory to R2 via rclone. Alternatively, we can mount R2 locally or use an S3-compatible backend wrapper. For server environments, configuring a local encrypted cache that automatically flushes to R2 provides the highest reliability during network fluctuations.
Let us install and configure rclone to map our Cloudflare R2 bucket:
sudo apt install -y rclone
Create an rclone configuration file at /root/.config/rclone/rclone.conf with the following structure:
[cloudflare-r2]
type = s3
provider = Cloudflare
access_key_id = YOUR_ACCESS_KEY_ID
secret_access_key = YOUR_SECRET_ACCESS_KEY
endpoint = https://YOUR_ACCOUNT_ID.r2.cloudflarestorage.com
acl = private
Constructing the Borgmatic Configuration
Borgmatic simplifies backup administration through a single, declarative YAML configuration file. We will define what to back up, where to store it, how to handle encryption, and our retention policies.
Generate a default configuration schema:
sudo mkdir -p /etc/borgmatic
sudo borgmatic config generate -o /etc/borgmatic/config.yaml
Step 3: Editing /etc/borgmatic/config.yaml
Open the file with your preferred text editor and modify it to reflect your business infrastructure needs. Below is a production-ready configuration template:
# /etc/borgmatic/config.yaml
location:
# Source directories to include in the backup
source_directories:
- /var/www
- /etc
- /home
# Paths to exclude from backups
exclude_patterns:
- '*.log'
- /var/www/html/cache
# Local repository path acting as our deduplication cache stage
repositories:
- /var/backup/borgrepository
storage:
# Encryption passphrase for local chunks
encryption_passphrase: "YOUR_SUPER_SECURE_PASSPHRASE_HERE"
retention:
# Retention policy for grandfather-father-son rotation schedule
keep_daily: 7
keep_weekly: 4
keep_monthly: 6
consistency:
# Run verification checks to ensure backup integrity
checks:
- repository
- archives
check_last: 3
hooks:
# Automating the sync to Cloudflare R2 post-backup
after_backup:
- echo "Starting sync to Cloudflare R2..."
- rclone sync /var/backup/borgrepository cloudflare-r2:vps-enterprise-backups/borgrepository
- echo "Sync completed successfully."
# Database dumps automated prior to file system snapshotting
postgresql_databases:
- name: application_db
username: postgres
Initializing the Encrypted Repository
Before running the automated pipeline, the Borg repository must be securely initialized with the specified encryption standard. Run the following command:
sudo borgmatic init --encryption repokey-blake2
This command sets up the repository metadata and securely embeds the encryption key within the repository folder itself, protected by your defined passphrase. Crucial: Back up your encryption_passphrase and the generated repository keys off-site immediately.
Automating the Pipeline with Systemd
To achieve a fully automated setup, we rely on Systemd timers rather than traditional cron jobs. Systemd provides granular execution tracking, advanced logging via journald, and better process control.
Step 4: Creating Systemd Service and Timer
Create the service unit file at /etc/systemd/system/borgmatic.service:
[Unit]
Description=Borgmatic Backup Service
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
Environment=PATH=/usr/local/bin:/usr/bin:/bin
ExecStart=/usr/local/bin/borgmatic --syslog --verbosity 1
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=/var/backup /var/log /root/.config/rclone
Next, define the execution schedule by creating the timer file at /etc/systemd/system/borgmatic.timer:
[Unit]
Description=Run Borgmatic Backup Daily
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
Enable and start the timer to activate the daily backup automation sequence:
sudo systemctl daemon-reload
sudo systemctl enable --now borgmatic.timer
You can check the status of your newly created automated backup schedule at any time with the following status lookup:
sudo systemctl status borgmatic.timer
Disaster Recovery: Validating and Restoring Backups
An untested backup strategy is a failed backup strategy. Disaster recovery validation checks ensure that when a critical infrastructure failure occurs, business operations can be resumed rapidly.
Listing Active Archives
To inspect what historical recovery points are stored inside your repository, execute:
sudo borgmatic rlist
Executing a Full Directory Restore
In the event of total local data corruption, pull down the latest repository state from Cloudflare R2 using rclone, and then use Borgmatic to unpack your archives securely:
# Fetch from Cloudflare R2
rclone sync cloudflare-r2:vps-enterprise-backups/borgrepository /var/backup/borgrepository
# Extract specific archive
sudo borgmatic extract --archive latest --path /var/www
Conclusion
By implementing an automated pipeline combining the advanced deduplication and client-side encryption capabilities of Borgmatic with the highly scalable, zero-egress-fee storage architecture of Cloudflare R2, you establish an optimized enterprise-grade disaster recovery solution. This layout guarantees zero-trust safety requirements while preserving predictable, cost-efficient infrastructure management fees. Monitor your system verification logs routinely to ensure ongoing data compliance and operational readiness.
