DEV Community

BRIAN MWOHI
BRIAN MWOHI

Posted on

How to Automate Encrypted Off-Site Linux Server Backups with Rclone and Cron

published: false
description: Build a zero-trust automated backup pipeline on Ubuntu 24.04 using Bash, Rclone client-side encryption, S3-compatible object storage, and Cron.

tags: linux, devops, security, bash

Relying solely on local disk snapshots or storing backups on the same virtual private server (VPS) leaves your infrastructure exposed to single points of failure. If the underlying host disk corrupts, an accidental rm -rf wipes a directory, or an attacker compromises the machine, local backups vanish right alongside your production data.

At the same time, uploading raw .tar.gz archives to cloud object storage introduces a privacy risk: configuration files, .env secrets, and database dumps sit unencrypted on a third-party provider's servers.

In this tutorial, you will build an automated, encrypted off-site backup pipeline on Ubuntu 24.04 LTS. You will write a defensive Bash script that archives critical server directories, encrypts both file contents and filenames locally using Rclone's crypt backend, uploads the archive to any S3-compatible bucket, enforces a 14-day retention policy, and runs automatically every night via Cron.

Backup Pipeline Overview

Every scheduled run follows this zero-trust workflow:

Local Directories (/etc/nginx, /var/www)
        │
        ▼
  Tar/Gzip Archive (/tmp/backup-YYYY-MM-DD.tar.gz)
        │
        ▼
  Rclone Crypt (Client-Side AES Encryption)
        │
        ▼
  S3-Compatible Object Storage (Scrambled Filenames & Data)
Enter fullscreen mode Exit fullscreen mode

Prerequisites

To follow along, you need:

  • An Ubuntu 24.04 LTS server with a non-root user that has sudo privileges.
  • An S3-compatible object storage bucket (such as AWS S3, Backblaze B2, DigitalOcean Spaces, or Cloudflare R2) along with an Access Key ID, Secret Access Key, and Endpoint URL.
  • Basic familiarity with the Linux command line and Bash scripting.

Step 1 — Install Rclone and Configure Your Base Cloud Remote

Ubuntu's default apt repositories often ship older versions of Rclone. Install the latest maintained release directly using Rclone's official installation script:

curl -fsSL https://rclone.org | sudo bash
Enter fullscreen mode Exit fullscreen mode

Verify the installation:

rclone version
Enter fullscreen mode Exit fullscreen mode

Expected output:

rclone v1.68.1
- os/version: ubuntu 24.04 (64 bit)
- os/kernel: 6.8.0-45-generic (x86_64)
- os/type: linux
- os/arch: amd64
Enter fullscreen mode Exit fullscreen mode

Because your backup script will run as root via Cron so it can read restricted system directories like /etc/nginx and /etc/letsencrypt, store your Rclone configuration under /root/.config/rclone/.

Create the configuration directory and open rclone.conf:

sudo mkdir -p /root/.config/rclone
sudo nano /root/.config/rclone/rclone.conf
Enter fullscreen mode Exit fullscreen mode

Add a base remote named [cloud-storage] using your S3-compatible provider credentials (the example below uses Backblaze B2 / generic S3 formatting):

[cloud-storage]
type = s3
provider = Other
access_key_id = YOUR_ACCESS_KEY_ID
secret_access_key = YOUR_SECRET_ACCESS_KEY
endpoint = ://backblazeb2.com
acl = private
Enter fullscreen mode Exit fullscreen mode

Note: If you use AWS S3, set provider = AWS, specify region = us-east-1, and omit the endpoint line.

Lock down the file permissions so non-root users on the server cannot read your cloud credentials:

sudo chmod 600 /root/.config/rclone/rclone.conf
Enter fullscreen mode Exit fullscreen mode

Test the connection by listing your bucket (replace my-server-backups-bucket with your actual bucket name):

sudo rclone lsd cloud-storage:my-server-backups-bucket
Enter fullscreen mode Exit fullscreen mode

If the command exits cleanly without errors, Rclone can authenticate with your storage bucket.


Step 2 — Layer Client-Side Encryption with Rclone crypt

Now wrap your [cloud-storage] remote inside an Rclone crypt remote. When you copy files to a crypt remote, Rclone encrypts both the file payload and the file name on your server before transmitting a single byte over the network.

First, generate two strong, random passwords to serve as your encryption key and salt:

openssl rand -base64 32
openssl rand -base64 32
Enter fullscreen mode Exit fullscreen mode

Rclone requires passwords inside rclone.conf to be obscured using rclone obscure. Run the command below twice—once for your primary password and once for your salt:

sudo rclone obscure "PASTE_FIRST_RANDOM_STRING_HERE"
sudo rclone obscure "PASTE_SECOND_RANDOM_STRING_HERE"
Enter fullscreen mode Exit fullscreen mode

Open /root/.config/rclone/rclone.conf again and append the [secure-backup] section at the bottom:

[secure-backup]
type = crypt
remote = cloud-storage:my-server-backups-bucket/encrypted
filename_encryption = standard
directory_name_encryption = true
password = YOUR_FIRST_OBSCURED_PASSWORD
password2 = YOUR_SECOND_OBSCURED_PASSWORD
Enter fullscreen mode Exit fullscreen mode

Verify Client-Side Encryption

Create a small test file, upload it through secure-backup:, and inspect how it appears in the underlying cloud-storage: bucket:

echo "sensitive production secret" | sudo tee /tmp/secret-test.txt > /dev/null
sudo rclone copy /tmp/secret-test.txt secure-backup:
Enter fullscreen mode Exit fullscreen mode

Compare what the decrypted view looks like versus what your cloud provider actually stores:

# View through the crypt remote (decrypted locally on the fly)
sudo rclone ls secure-backup:

# View the raw bucket contents (what your cloud provider sees)
sudo rclone ls cloud-storage:my-server-backups-bucket/encrypted
Enter fullscreen mode Exit fullscreen mode

Output:

       28 secret-test.txt
       76 8f9k2m4p7q1v9x3z5b8n0c4w2y6r1t5l
Enter fullscreen mode Exit fullscreen mode

Your cloud provider only sees a scrambled filename (8f9k2m4p7q...) and encrypted bytes. Clean up the test file before moving on:

sudo rm -f /tmp/secret-test.txt
sudo rclone deletefile secure-backup:secret-test.txt
Enter fullscreen mode Exit fullscreen mode

Step 3 — Write the Automated Backup and Retention Script

Next, create a standalone Bash script that packages your target directories, uploads the compressed tarball to secure-backup:, deletes the local temporary archive, and prunes remote backups older than 14 days.

Create /usr/local/bin/server-backup.sh:

sudo nano /usr/local/bin/server-backup.sh
Enter fullscreen mode Exit fullscreen mode

Paste the following script:

#!/usr/bin/env bash
set -euo pipefail

# Configuration
TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")
HOSTNAME=$(hostname -s)
BACKUP_NAME="${HOSTNAME}-backup-${TIMESTAMP}.tar.gz"
TMP_DIR="/tmp/server-backups"
ARCHIVE_PATH="${TMP_DIR}/${BACKUP_NAME}"
REMOTE_DEST="secure-backup:"
RETENTION_DAYS="14d"

# Directories to back up (customize for your environment)
SOURCE_DIRS=(
  "/etc/nginx"
  "/etc/letsencrypt"
  "/var/www"
)

# Ensure temporary directory exists and clean up on exit
mkdir -p "${TMP_DIR}"
trap 'rm -rf "${TMP_DIR}"' EXIT

echo "[$(date -Iseconds)] Starting backup: ${BACKUP_NAME}"

# Create compressed archive (ignore missing optional directories gracefully if needed)
tar -czf "${ARCHIVE_PATH}" "${SOURCE_DIRS[@]}"

# Upload encrypted archive to object storage
/usr/bin/rclone copy "${ARCHIVE_PATH}" "${REMOTE_DEST}" --config /root/.config/rclone/rclone.conf

echo "[$(date -Iseconds)] Upload complete. Pruning backups older than ${RETENTION_DAYS}..."

# Delete remote backups older than 14 days
/usr/bin/rclone delete "${REMOTE_DEST}" --min-age "${RETENTION_DAYS}" --config /root/.config/rclone/rclone.conf

echo "[$(date -Iseconds)] Backup finished successfully."
Enter fullscreen mode Exit fullscreen mode

Why This Script Uses set -euo pipefail and trap

  • set -euo pipefail forces the script to abort immediately if tar fails or rclone encounters a network error, preventing broken or empty archives from being treated as successful runs.
  • trap 'rm -rf "${TMP_DIR}"' EXIT guarantees the local .tar.gz file in /tmp is deleted whether the script succeeds or fails, preventing your VPS disk from filling up over time.

Make the script executable only by root:

sudo chmod 700 /usr/local/bin/server-backup.sh
Enter fullscreen mode Exit fullscreen mode

Run a manual test execution now and confirm the encrypted archive lands in your remote bucket:

sudo /usr/local/bin/server-backup.sh
sudo rclone ls secure-backup:
Enter fullscreen mode Exit fullscreen mode

Expected output:

[2026-11-22T10:15:02+00:00] Starting backup: ubuntu-prod-backup-2026-11-22_10-15-02.tar.gz
[2026-11-22T10:15:04+00:00] Upload complete. Pruning backups older than 14d...
[2026-11-22T10:15:05+00:00] Backup finished successfully.
    14820 ubuntu-prod-backup-2026-11-22_10-15-02.tar.gz
Enter fullscreen mode Exit fullscreen mode

Step 4 — Schedule Daily Backups with Cron

With the script verified, schedule it to run automatically every night at 02:00 AM using root's crontab.

Open root's crontab editor:

sudo crontab -e
Enter fullscreen mode Exit fullscreen mode

Add the following line at the bottom of the file:

0 2 * * * /usr/local/bin/server-backup.sh >> /var/log/server-backup.log 2>&1
Enter fullscreen mode Exit fullscreen mode

This schedules the script for minute 0, hour 2 every day, and appends both standard output (stdout) and errors (stderr) to /var/log/server-backup.log.

To prevent /var/log/server-backup.log from growing indefinitely over months of operation, create a simple logrotate rule:

sudo tee /etc/logrotate.d/server-backup > /dev/null <<'EOF'
/var/log/server-backup.log {
    weekly
    rotate 4
    compress
    missingok
    notifempty
}
EOF
Enter fullscreen mode Exit fullscreen mode

Step 5 — Test a Full Disaster Recovery Restore

A backup strategy is only as reliable as your last restore test. Verify that you can download and decrypt an archive back onto a clean directory:

mkdir -p /tmp/restore-test
sudo rclone copy secure-backup: /tmp/restore-test/ --max-age 1h --config /root/.config/rclone/rclone.conf
ls -lh /tmp/restore-test/
Enter fullscreen mode Exit fullscreen mode

Extract the downloaded archive into /tmp/restore-test/extracted and inspect the restored directory tree:

mkdir -p /tmp/restore-test/extracted
tar -xzf /tmp/restore-test/*.tar.gz -C /tmp/restore-test/extracted
ls -la /tmp/restore-test/extracted/etc/nginx
Enter fullscreen mode Exit fullscreen mode

Top comments (0)