Back to articles
Technology Insight

Automating Secure VPS Backups: How to Configure Borgmatic with Cloudflare R2 for Daily Encrypted Backups

May 30, 2026

Introduction: The Critical Need for Automated VPS Backups

In the digital enterprise landscape, data is arguably an organization’s most valuable asset. Whether you are running a high-traffic e-commerce platform, a client-facing SaaS application, or a critical corporate database on a Virtual Private Server (VPS), data loss can be catastrophic. Hardware failures, human errors, malicious cyberattacks, and corrupted software updates pose constant threats to operational continuity.

To mitigate these risks, a robust, automated, and encrypted backup strategy is non-negotiable. However, traditional backup methods often suffer from inefficiency, high storage costs, or complex restoration procedures. This guide offers a modern, enterprise-grade solution: combining Borgmatic, a powerful configuration-driven wrapper for the deduplicating backup program BorgBackup, with Cloudflare R2, an ultra-affordable, zero-egress-fee S3-compatible object storage solution. By the end of this tutorial, you will have a fully automated, daily encrypted backup pipeline safeguarding your VPS infrastructure.

Why Borgmatic and Cloudflare R2?

Before diving into the technical implementation, it is important to understand why this specific technology stack represents a gold standard for modern infrastructure management.

  • Borgmatic (BorgBackup): Offers secure, authenticated, and client-side encrypted backups. It utilizes deduplication techniques to ensure that only modified data chunks are uploaded, drastically reducing storage footprints and bandwidth usage. Borgmatic simplifies this via declarative YAML configuration files.
  • Cloudflare R2: Unlike traditional cloud storage providers, Cloudflare R2 charges zero egress fees. This means restoring your data—even terabytes of it—in an emergency will not result in a surprise bill. It provides high durability, availability, and seamless compatibility with the Amazon S3 API.
---

Prerequisites and Environment Setup

To successfully follow this guide, ensure your environment meets the following requirements:

  1. A Linux-based VPS (this guide assumes Ubuntu 22.04 LTS or Ubuntu 24.04 LTS).
  2. Root or sudo administrative privileges on the server.
  3. A Cloudflare account with R2 storage enabled.

Step 1: Creating a Cloudflare R2 Bucket and API Credentials

First, we must provision our remote storage destination and generate the cryptographic keys required for our VPS to securely communicate with Cloudflare R2.

  1. Log in to your Cloudflare Dashboard and navigate to the R2 section in the sidebar.
  2. Click Create bucket. Name your bucket descriptively (e.g., vps-prod-backups) and select your preferred data location hint, then click Create bucket.
  3. Navigate back to the main R2 page and click on Manage R2 API Tokens on the right-hand side.
  4. Click Create API token. Provide a token name, set permissions to Edit (required to write backups), and scope it to your specific bucket for maximum security.
  5. Click Create Token and securely copy the Access Key ID, Secret Access Key, and the S3 Endpoint URL. Note: These credentials will not be shown again.
---

Installing BorgBackup, Borgmatic, and Rclone on the VPS

Since BorgBackup does not natively support direct S3 protocols out of the box, we will utilize Rclone as a bridge to sync our local encrypted Borg repositories to Cloudflare R2. Borgmatic will orchestrate the entire workflow.

Updating the System and Installing Dependencies

Connect to your VPS via SSH and execute the following commands to ensure all system repositories are up to date:

sudo apt update && sudo apt upgrade -y
sudo apt install borgbackup rclone python3-pip -y

Next, install Borgmatic using the official package manager or via pip3 to ensure you have the latest version containing modern configuration options:

sudo pip3 install --upgrade borgmatic

Configuring Rclone for Cloudflare R2

We need to configure Rclone to recognize our Cloudflare R2 bucket as a remote storage target. Run the interactive configuration tool:

rclone config

Follow the interactive prompts to create a new remote:

  • Enter n for a new remote and name it cloudflare_r2.
  • Choose storage type: Select Amazon S3 Compliant Storage (usually option number 4 or similar depending on the version).
  • Choose provider: Select Any other S3 compatible provider.
  • Enter AWS Access Key: Paste your Cloudflare R2 Access Key ID.
  • Enter AWS Secret Key: Paste your Cloudflare R2 Secret Access Key.
  • Endpoint: Enter your Cloudflare R2 S3 Endpoint URL (e.g., https://.r2.cloudflarestorage.com).
  • Leave remaining fields (Region, ACL) as default or blank.

Test the connection by listing your buckets:

rclone lsd cloudflare_r2:

If configured correctly, your newly created bucket will be displayed in the terminal output.

---

Configuring Borgmatic for Automated Backups

Borgmatic relies on a central configuration file to define what to back up, where to store it, and how to handle retention policies.

Generating the Configuration Template

Generate a default configuration schema using the Borgmatic CLI tool:

sudo generate-borgmatic-config

This creates a file located at /etc/borgmatic/config.yaml. Open this file in your preferred text editor (such as nano):

sudo nano /etc/borgmatic/config.yaml

Customizing the Configuration File

Replace or modify the file content to match the optimized schema below. Ensure you update the directory paths, database credentials, and repository locations according to your infrastructure specifications.

# /etc/borgmatic/config.yaml

location:
    # List of source directories to back up
    source_directories:
        - /var/www
        - /etc
        - /home

    # Local paths to Borg repositories
    repositories:
        - /var/backup/vps-repo

storage:
    # Passphrase to encrypt the Borg repository safely
    encryption_passphrase: "YOUR_SUPER_SECURE_PASSPHRASE_HERE"

retention:
    # Define backup retention schedules (Pruning policy)
    keep_daily: 7
    keep_weekly: 4
    keep_monthly: 6

consistency:
    # Check consistency of repositories periodically
    checks:
        - repository
        - archives
    check_last: 3

hooks:
    # Commands to execute after a successful local backup
    after_backup:
        - echo "Local backup completed successfully. Syncing to Cloudflare R2..."
        - rclone sync /var/backup/vps-repo cloudflare_r2:vps-prod-backups/vps-repo --progress
    
    # Database backup hooks (Optional but recommended for stateful apps)
    postgresql_databases:
        - name: all
          username: postgres

Security Warning: Treat the encryption_passphrase and your /etc/borgmatic/config.yaml file with strict confidentiality. Restrict file permissions using sudo chmod 600 /etc/borgmatic/config.yaml to guarantee that only the root user can read its contents.

---

Initializing the Encrypted Borg Repository

Before Borgmatic can execute backups, the target repository directory must be initialized with the chosen encryption standard. Run the initialization command via Borgmatic:

sudo borgmatic init --encryption repokey-blake2

This command safely creates the local backup repository at /var/backup/vps-repo and embeds the encryption key securely. A copy of the key will be encrypted with your passphrase.

Executing the First Manual Backup Test

To verify that the entire workflow—from local deduplication to Cloudflare cloud synchronization—functions seamlessly, execute a manual backup run with verbose output:

sudo lib/borgmatic/borgmatic create --verbosity 1 --progress

Monitor the terminal output. You should observe Borgmatic scanning your directories, compressing and deduplicating chunks, and finally executing the rclone sync command to upload the repository data to Cloudflare R2.

---

Automating the Pipeline with Systemd and Cron

To achieve true peace of mind, the backup process must be entirely autonomous. We can leverage systemd timers or a traditional cron job to handle daily scheduling.

Option A: Using Systemd Timers (Recommended)

Modern Linux distributions prefer systemd timers due to their superior logging via journalctl. Borgmatic frequently provides pre-built systemd service files upon installation.

Enable and start the Borgmatic systemd timer to run automatically every day:

sudo systemctl enable borgmatic.timer
sudo systemctl start borgmatic.timer

Check the status of your timer using:

sudo systemctl status borgmatic.timer

Option B: Using Cron

If your system utilizes standard cron daemons, you can schedule the backup by editing the root crontab:

sudo crontab -e

Add the following line to execute Borgmatic every night at 2:00 AM system time:

0 2 * * * /usr/local/bin/borgmatic --syslog --ini /etc/borgmatic/config.yaml
---

Monitoring and Verification: Ensuring Restorability

A backup strategy is only as good as its restore execution. Periodically verifying data integrity is a core pillar of system administration.

Listing Existing Archives

To view the historical index of all successful daily backups stored within your repository, execute:

sudo borgmatic list

Simulating Data Restoration

To extract and restore a specific archive or file to an isolated directory for testing, utilize the extract flag:

# Extract an entire archive to the current working directory
sudo borgmatic extract --archive vps-prod-backups-2026-05-30

Conclusion

By automating your VPS backup architecture using Borgmatic and Cloudflare R2, you have built a resilient, secure, and cost-effective disaster recovery mechanism. Your data is deduplicated locally to save space, encrypted client-side to maintain strict privacy, and replicated to enterprise-grade object storage with zero egress financial penalties. Regularly monitor your cron logs, verify backup states, and conduct dry-run restorations annually to ensure your infrastructure remains entirely bulletproof.

Automating Secure VPS Backups: How to Configure Borgmatic with Cloudflare R2 for Daily Encrypted Backups | DPTCloud