How to Back Up Linux Servers to S3: Restic and Recovery Guide

Create encrypted Linux backups with Restic, stage database-consistent inputs, and prove recovery with a fresh-directory restore and file hashes.

Adrian Silaghi

12 min read

2,002 views

linuxserverbackups3object storageresticrcloneduplicitymysqlpostgresql
How to Back Up Linux Servers to S3: Restic and Recovery Guide

Linux servers are the backbone of modern infrastructure. Whether you're running web applications, databases, or microservices, reliable backups are non-negotiable. S3-compatible storage can provide an off-host destination, provided you protect the credentials and prove you can recover the data.

This guide covers three battle-tested methods: Restic (modern, encrypted, deduplicated), rclone (simple sync), and Duplicity (GPG-encrypted incremental backups).

Updated 2 November 2026. This expanded guide includes a fresh-directory recovery fixture, SHA-256 verification and failure checks. The recorded fixture uses a local Restic repository; it does not prove any S3 endpoint, database consistency or whole-server recovery.

Why S3 for Server Backups?

Feature Local/NAS Rsync to Server S3 Storage
Geographic Redundancy No Manual setup Depends on provider and region
Durability RAID dependent Server dependent Provider-specific documented durability
Maintenance Hardware, RAID Second server Provider operates storage; you operate backup/recovery
Scalability Buy more drives Limited Subject to quotas and capacity
Cost per TB $50-100 drives $5-10/mo server See current storage plan
API Access No SSH only Standard S3 API

What You'll Need

  • Linux server (Ubuntu, Debian, RHEL, CentOS, etc.)
  • Root or sudo access
  • S3-compatible storage credentials:
    • Endpoint and region: copy the exact values from your bucket connection details
    • Access Key ID
    • Secret Access Key
    • Bucket name

Method 1: Restic (Recommended)

Restic is a modern backup program designed for security and efficiency. It provides encryption, deduplication, and integrity verification out of the box.

Why Choose Restic?

  • AES-256 encryption (client-side, password-protected)
  • Content-defined chunking and deduplication
  • Fast incremental backups
  • Easy restore (mount backups as filesystem)
  • Cross-platform (Linux, Mac, Windows)
  • Active development and community

Step 1: Install and record a supported Restic version

Install Restic through your distribution's supported package or a release from the official release page. Match the architecture and verify the published release checksums. Do not combine a hard-coded old filename with a latest download URL.

# Ubuntu/Debian example
sudo apt-get update
sudo apt-get install restic
restic version

Record this version in each recovery drill. Test restoration with the version you will have available on a replacement host, including repository-format compatibility.

Step 2: Protect S3 credentials and the repository password

Create /root/.restic-env with owner-only permissions before writing secrets into it. Populate it through your approved secret manager or a local editor; keep it out of source control and command transcripts.

# Example file contents: replace placeholders locally.
export AWS_ACCESS_KEY_ID='YOUR_BACKUP_ACCESS_KEY'
export AWS_SECRET_ACCESS_KEY='YOUR_BACKUP_SECRET_KEY'
export AWS_DEFAULT_REGION='YOUR_BUCKET_REGION'
export RESTIC_REPOSITORY='s3:https://YOUR_ENDPOINT/YOUR_BUCKET/server-backup'
export RESTIC_PASSWORD_FILE='/root/.restic-password'

Use umask 077 before creating both files and restrict them with chmod 600. Keep the repository password recoverable independently of the server. Losing it makes encrypted backups unusable. Give the backup key only the bucket/prefix permissions needed by your tested Restic workflow. Repository locks and maintenance may require writes/deletes; a read-only restore credential can be a separate role.

Use the exact bucket endpoint and region provided by the storage service. Keep TLS verification enabled. Never point bucket lifecycle expiration at active Restic repository objects: arbitrary deletion can corrupt the repository. Object Lock/versioning may need a separately tested repository design and is not assumed here.

Step 3: Initialize Repository

# Source credentials
source /root/.restic-env

# Initialize repository (first time only)
restic init

# Expected output:
# Repository created at the configured RESTIC_REPOSITORY

Step 4: Back up recoverable inputs

Back up configuration, user files and completed database exports. Do not point Restic at a live MySQL or PostgreSQL data directory and assume file presence means a usable database. Use the database's supported dump/physical-backup procedure, or a genuinely quiesced coherent snapshot with the required logs. Application uploads and the database may need a coordinated write freeze to describe one recovery point.

source /root/.restic-env
# Prepare /srv/backup-inputs with completed database exports first.
restic backup /etc /srv/backup-inputs --tag server-daily --verbose
# Add /home and application uploads after reviewing exclusions and consistency.
restic snapshots --tag server-daily

Keep application code or an exact deployable release artifact and dependency lockfiles. Excluding vendor or node_modules is only safe when the recovery environment can reproduce the same dependencies. A file backup is not a complete bootable server image.

Step 5: View and Manage Snapshots

# List all snapshots
restic snapshots

# List snapshots with specific tag
restic snapshots --tag webapps

# Show detailed info about a snapshot
restic stats
restic stats latest

# Find files in backups
restic find "*.conf"
restic find --snapshot latest "nginx.conf"

Step 6: Automate with observable failures

Download the backup script and recovery fixture. The Linux script serializes runs, requires prepared inputs, and fails the job when Restic fails. It deliberately separates destructive retention maintenance from daily backup.

#!/usr/bin/env bash
set -euo pipefail
umask 077
exec 9>/run/lock/restic-server-backup.lock
flock -n 9 || { printf '%s\n' 'Another backup is running' >&2; exit 1; }
# This owner-only file must be populated by the operator before scheduling.
source /root/.restic-env
: "${RESTIC_REPOSITORY:?Set RESTIC_REPOSITORY}"
: "${RESTIC_PASSWORD_FILE:?Set RESTIC_PASSWORD_FILE}"
test -r "$RESTIC_PASSWORD_FILE"
test -d /srv/backup-inputs
trap 'printf "%s\n" "Backup failed; inspect the service journal" >&2' ERR
# Only completed, database-consistent exports belong in this staging directory.
restic backup /etc /srv/backup-inputs --tag server-daily

Install the reviewed script at /usr/local/bin/restic-backup.sh with executable permissions. Prepare /srv/backup-inputs before enabling a schedule. Treat incomplete or partially readable input as a failed backup; do not convert a nonzero exit into a success message. Monitor the service result and the age of the last successful snapshot independently.

Step 7: Schedule with Cron

# Edit crontab
crontab -e

# Daily backup at 3 AM
0 3 * * * /usr/local/bin/restic-backup.sh

# Or use systemd timer (recommended for modern systems)
cat > /etc/systemd/system/restic-backup.service << 'EOF'
[Unit]
Description=Restic Backup
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/restic-backup.sh
User=root
EOF

cat > /etc/systemd/system/restic-backup.timer << 'EOF'
[Unit]
Description=Daily Restic Backup

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
RandomizedDelaySec=1800

[Install]
WantedBy=timers.target
EOF

# Enable timer
systemctl daemon-reload
systemctl enable restic-backup.timer
systemctl start restic-backup.timer

# Check timer status
systemctl list-timers restic-backup.timer

Restoring to a replacement host

Install the recorded client version, retrieve credentials and password from independent storage, and restore into a new empty directory. Select an explicit snapshot ID after checking host, tag, timestamp and paths. Restoring latest from a shared repository without filters can choose the wrong machine.

source /root/.restic-env
restic snapshots --tag server-daily
# Replace SNAPSHOT_ID with the chosen immutable snapshot identifier.
restic ls SNAPSHOT_ID
restic check --read-data
restore_target=$(mktemp -d /tmp/restic-restore.XXXXXXXX) || exit 1
restic restore SNAPSHOT_ID --target "$restore_target"

Absolute source paths are reproduced below the target: /etc/nginx/nginx.conf becomes $restore_target/etc/nginx/nginx.conf. Compare expected file hashes and permissions. Restore a database archive into a disposable database, then run exact data and application checks before deciding it is usable. The official restore guide explains snapshot/path selection.

Do not restore directly to / during a drill. Review configuration differences, ownership, service versions, credentials and host keys before moving recovered files into service. Record the recovery point, bytes, verification result and elapsed time; a successful decrypt does not prove the application starts.

Run the downloadable recovery fixture

Run python3 lab.py with a local Restic binary and Python 3. It creates a temporary local repository, backs up two synthetic files, reads all repository data, restores into a fresh directory, compares every SHA-256 hash, and confirms that an incorrect password and a missing source both fail. It cleans up only its own temporary directory. The download includes the recorded version and results.

This fixture checks Restic recovery mechanics on a local backend. It does not contact S3 or restore a database. Repeat the same drill against a disposable prefix of your actual bucket with your endpoint, region, credentials and client version. For application/database archive validation, use the PostgreSQL rehearsal fixture.

Method 2: Rclone (Simple Sync)

Rclone provides simple file synchronization without deduplication or encryption (though crypt overlay is available).

Install and configure rclone

Install a supported release using the official installation instructions. Configure an S3 remote named s3backup using the endpoint, region and credentials from your bucket details. Keep its credential-bearing configuration owner-only. Record rclone version and test connectivity against a disposable prefix before scheduling transfers.

Copy instead of an unversioned destructive mirror

A bare rclone sync propagates deletion from source to destination. That is useful mirroring behavior but an unsafe default for a recovery copy. Use a unique timestamped prefix and copy for completed inputs; keep a separate reviewed retention policy.

set -euo pipefail
stamp=$(date -u +%Y%m%dT%H%M%SZ)
rclone copy /srv/backup-inputs "s3backup:YOUR_BUCKET/$(hostname)/$stamp"   --log-level INFO
rclone check /srv/backup-inputs "s3backup:YOUR_BUCKET/$(hostname)/$stamp"   --download

Configure the remote with the bucket's actual endpoint and region, and review provider-specific checksum behavior. Rehearse a copy back to a blank directory and validate content. A timestamped prefix does not itself add encryption, application consistency or an independent credential boundary.

Method 3: Duplicity (GPG Encrypted)

Duplicity creates encrypted incremental backups using GPG encryption.

Install Duplicity

# Ubuntu/Debian
apt install duplicity python3-boto3 -y

# RHEL/CentOS
dnf install duplicity python3-boto3 -y

Configure and run a version-specific Duplicity workflow

Duplicity creates encrypted full/incremental backup chains. The current official manual documents the boto3 S3 backend, endpoint handling and restore syntax. Check your installed version and backend dependencies before use. The triple slash in this backend URL is intentional; the bucket is not the endpoint hostname.

# Credentials and encryption passphrase must already be supplied securely.
# Use a disposable bucket/prefix for a rehearsal.
duplicity --version
duplicity full /srv/backup-inputs   --s3-endpoint-url https://YOUR_ENDPOINT   s3:///YOUR_BUCKET/duplicity/application
# Restore into a new empty directory with the same configured endpoint.
duplicity restore --s3-endpoint-url https://YOUR_ENDPOINT   s3:///YOUR_BUCKET/duplicity/application /restore-duplicity

Verify the restored files and recover the required full/incremental chain with independently available keys. This guide's downloadable lab tests Restic only; no Duplicity S3 upload/restore was run.

Database-consistent inputs before Restic

MySQL and MariaDB: completed logical exports

Use the matching vendor client and an owner-only client option file. --single-transaction applies to transactional tables; avoid concurrent DDL and handle nontransactional tables separately. Review routines, triggers, events, users/grants, definer clauses and GTID/version options. Never treat a successful gzip of a failed dump as success.

set -euo pipefail
umask 077
mkdir -p /srv/backup-inputs
# Write a temporary name and publish only a completed dump.
mysqldump --defaults-extra-file=/root/.mysql-backup.cnf   --single-transaction --routines --triggers --events   --databases application > /srv/backup-inputs/application.sql.partial
mv /srv/backup-inputs/application.sql.partial /srv/backup-inputs/application.sql
# Run Restic only after the export succeeds.
restic backup /srv/backup-inputs/application.sql --tag mysql

Restore this export into an isolated compatible server and verify real tables, generated IDs and application behavior. Native physical backup tools need their own prepare/restore procedure. Copying a running /var/lib/mysql directory is not that procedure.

PostgreSQL: schema, data and permissions

Create a protected libpq service named backup_source with verified TLS and credentials outside command history. A database archive includes one database; cluster roles need separate inventory/export and a reviewed recovery plan.

set -euo pipefail
umask 077
mkdir -p /srv/backup-inputs
pg_dump --dbname='service=backup_source' --format=custom   --file=/srv/backup-inputs/application.dump.partial
mv /srv/backup-inputs/application.dump.partial /srv/backup-inputs/application.dump
restic backup /srv/backup-inputs/application.dump --tag postgres

In a scratch environment, provision required roles, restore with pg_restore --exit-on-error, and test exact totals, constraints, extensions, policies and sequences. A logical dump is not continuous point-in-time recovery. For PITR, use a supported base-backup/WAL arrangement and prove its recovery chain. See the PostgreSQL validation and cutover guide for the local fixture.

MongoDB and other databases

Use each engine's supported consistency and restore procedure. A mongodump of a changing deployment has topology and consistency requirements; do not generalize the filesystem example into a universal database backup. Record the tool/server versions and restore the result in isolation. No MySQL, MariaDB or MongoDB restore was performed for this article.

What to Back Up on Linux Servers

Directory Priority Contents
/etc Critical System and app configurations
/var/www Critical Web applications
/home High User data
/var/lib/mysql Critical Live database files: use a supported consistent export or backup
/var/lib/postgresql Critical Live database files: use a supported base/WAL or logical backup
/opt Medium Third-party applications
/root High Root user files, scripts
/var/log Medium Logs (optional, often large)

Best Practices

1. Use Encryption

Always encrypt backups, especially if they contain sensitive data. Restic encrypts by default.

2. Test restores using explicit recovery points

Select an explicit snapshot ID after checking the host, tag, timestamp and included paths. Create a fresh target directory for each drill, compare expected hashes and permissions, and restore databases into isolated services before accepting the recovery point. Retain the drill evidence; clean up only its known disposable paths after review.

3. Monitor backup health and recovery health separately

Alert on a failed systemd unit, a missing recent successful snapshot, an overdue integrity check and an overdue recovery drill. A timer can run successfully while its input export is stale. Include export freshness in the job's success conditions. Restic's backup documentation distinguishes complete success from incomplete source reads; preserve the nonzero status.

4. Review retention before pruning

Choose retention from your recovery objectives and legal requirements. First inspect the effect with a dry run and explicit host/tag grouping. Only a separately authorized maintenance job should remove snapshots or prune repository data.

restic forget --tag server-daily --group-by host,paths,tags   --keep-daily 7 --keep-weekly 4 --keep-monthly 12 --dry-run

A dry run does not delete data. Review the selected snapshots before removing --dry-run; plan prune separately and keep independent recovery copies. Do not apply bucket lifecycle expiration directly to Restic's active repository keys.

5. Verify Backup Integrity

# Weekly integrity check (reads 10% of data)
restic check --read-data-subset=10%

# Monthly full check
restic check --read-data

Comparison: Restic vs Rclone vs Duplicity

Feature Restic Rclone Duplicity
Encryption Built-in AES-256 Via crypt overlay GPG
Deduplication Yes No Incremental delta chain
Incremental Always Skips unchanged files; no snapshot history Yes
Versioning Built-in No (S3 versioning) Built-in
Recovery validationRestore selected snapshot and verifyCopy back and verifyRecover the required full/incremental chain and verify
Best For Most use cases Simple sync GPG users

Get Started

Set up an off-host destination and prove recovery before relying on it:

  1. Create a DanubeData account
  2. Create a storage bucket
  3. Generate access keys
  4. Install Restic and follow this guide

Create Your Backup Bucket - See current Object Storage pricing

Your servers deserve better than local backups that can fail alongside them.

Questions about server backup strategy? Contact our team—we manage Linux servers ourselves and understand the challenges.

Sources and recovery scope

Use the official repository integrity documentation, rclone copy documentation and PostgreSQL SQL dump backup documentation alongside your database vendor's version-specific procedure. DanubeData Object Storage is a possible destination; confirm current price, location, quotas and recovery access before use.

A complete acceptance test recovers from another host using independently available credentials, proves file hashes and database/application behavior, and records an achievable recovery time and recovery point. The small downloadable fixture proves only its explicitly listed local checks.

Browse all articles
Tutorials7 min read

Raport zilnic de stoc WooCommerce cu n8n

Importă un workflow n8n pentru raportul de stoc WooCommerce: paginare, variații, praguri și controlul retrimiterilor, cu acces doar de citire în magazin.

Adrian Silaghi109 views

Ready to get started?

Deploy your infrastructure in minutes with DanubeData's managed services.