Troubleshooting

How to Back Up a Linux Server with restic: Encrypted Backups to S3-Compatible Storage

Aseem Kishore
22 min read

The Back Room Tech is reader-supported. We may earn a commission when you buy through links on our site. Learn more.

This guide walks through backing up a Linux server with restic to S3-compatible storage. You’ll end up with encrypted, deduplicated snapshots on a systemd timer, a retention policy that cleans up old snapshots, and a tested restore that proves the backups work.

The short version: install restic and put your S3 keys and repository password in root-only files with 600 permissions. Point RESTIC_REPOSITORY at your bucket and run restic init. Then schedule restic backup and restic forget --prune with a systemd service and timer. Finally, restore to a scratch directory on a regular basis. Plenty of tutorials stop at “backup succeeded.” This one keeps going until you’ve restored real files.

What Is restic?

restic is a free, open-source command-line backup program. It runs on Linux, and also on Windows, macOS, and BSD. There’s no GUI for this workflow. Everything happens in the shell, which suits a headless server fine.

Three features set it apart from a homemade tar or rsync script:

  • Client-side encryption. Data is encrypted on your server before it’s uploaded. The storage provider only ever sees encrypted blobs. The trade-off is strict: according to the restic documentation, if you lose the repository password, you lose the data. There’s no recovery path.
  • Deduplication across snapshots. Each run creates a new snapshot, but restic only uploads data that changed. A nightly backup of a mostly static server costs far less storage and bandwidth than nightly tarballs.
  • A built-in snapshot model. You can list snapshots, check repository integrity, restore one file or a whole snapshot, and expire old snapshots with a retention policy. With rsync you’d have to build all of that yourself.

restic can write to a local disk, SFTP, a REST server, or object storage. That includes Amazon S3 and any S3-compatible service, such as self-hosted MinIO or a third-party provider. restic itself costs nothing. Only your storage provider charges you.

Now the weak spot. restic has no server-side component that enforces append-only behavior on plain S3. If an attacker gets root on the server, they also get your S3 keys and repository password. Plan your bucket permissions with that in mind (see Configuration).

Prerequisites

  • A Linux server with root or sudo access over SSH
  • systemd as the init system (used for the timer in Step 10)
  • An account with an S3-compatible object storage provider, or a self-hosted MinIO instance (for example on a NAS Hard Drive or Mini PC for Homelab elsewhere on your network)
  • Outbound HTTPS access from the server to your storage provider’s endpoint
  • A password manager, or an encrypted USB flash drive, for an off-server copy of the repository password
  • Some time set aside for the first setup, commonly in the 30–45 minute range, though the actual time depends on your server, how much data you’re backing up, and your upload speed, since most of it is spent waiting for the first upload
RequirementDetails
OSAny systemd-based Linux distribution. Commands are written for Ubuntu/Debian-family systems; paths are noted where they can differ
resticA current release from your distro or GitHub releases. Check yours with restic version
StorageAn empty S3-compatible bucket plus an access key ID and secret key
PrivilegesRoot. Backing up /etc and other system paths requires it

Note on versions: This guide doesn’t pin a specific restic version. restic flags occasionally change between releases. If a command here behaves differently on your system, restic help <command> is the authority for the version you have installed.

Step-by-Step Guide

Step 1: Install restic and Verify the Version

You have two options:

  • Distribution package. Most major distributions ship a package named restic. Install it with your normal package manager. Distro packages can lag behind upstream, so check the version once it’s installed.
  • Official release binary. Download the Linux build for your CPU architecture from the restic releases page. Release binaries are compressed single files. Decompress the file, make it executable, and move it into your PATH:
# Replace the filename with the exact file you downloaded from the releases page
bunzip2 restic_VERSION_linux_amd64.bz2
chmod +x restic_VERSION_linux_amd64
sudo mv restic_VERSION_linux_amd64 /usr/local/bin/restic

Then confirm restic is installed and note where it lives. You’ll need the full path for the systemd unit later.

restic version
command -v restic

Expected output (your version, Go version, and path will differ):

restic X.Y.Z compiled with goX.Y.Z on linux/amd64
/usr/bin/restic

Distro packages usually install to /usr/bin/restic. A manual install like the one above lives at /usr/local/bin/restic.

Terminal showing the output of `restic version` and `command -v restic`, with the version string and binary path visible

Step 2: Create an S3-Compatible Bucket and Access Key

This step happens in your storage provider’s console or CLI. Menu labels differ between providers, so look for these three things:

  • Create a new, empty bucket for restic only, for example myserver-restic. Keep it private. Don’t enable public access.
  • Find the S3 endpoint URL for that bucket’s region. On Scaleway, for example, it’s shown under Bucket settings > Bucket Information (per Scaleway’s restic tutorial). Other providers put it in their own docs or on the bucket details page.
  • Create an access key and secret key. If your provider supports scoped keys or bucket policies, limit this key to the single restic bucket. Don’t reuse an account-wide admin key.

Write down three values. You’ll need them in the next step:

ValueExample placeholder
Endpoints3.example-provider.com
Bucket namemyserver-restic
Access key ID / secret keyYOUR_ACCESS_KEY_ID / YOUR_SECRET_ACCESS_KEY

For Amazon S3 itself, the endpoint is s3.amazonaws.com. Storage pricing varies by provider and region, so check your provider’s own pricing page, such as AWS S3 pricing. This guide doesn’t quote figures.

Step 3: Generate the Repository Password and Store It Securely

The repository password and the S3 secret key are two separate secrets. The S3 key gets you into the bucket. The restic password decrypts what’s inside it. One can’t stand in for the other.

Work as root for the rest of the setup so file ownership comes out right:

sudo -i

Create a root-only config directory and generate a long random password:

# 700 = only root can list or enter this directory
install -d -m 700 /etc/restic

# Generate a 32-byte random password, base64-encoded
openssl rand -base64 32 > /etc/restic/password

# 600 = only root can read or write the file
chmod 600 /etc/restic/password

Verify the permissions:

ls -l /etc/restic/

Expected output (illustrative — your timestamp and exact file size will differ):

-rw——- 1 root root 45 Oct 25 10:12 password

Warning: Copy this password somewhere off the server now, before you back up any data. Use a password manager or an encrypted USB drive kept in a separate place. If the server dies, the password file dies with it, and your off-site backup becomes a pile of unreadable encrypted blobs.

Step 4: Create the 600-Permission Environment File

restic reads its repository location and credentials from environment variables. Put them in one file that both your interactive shell and systemd can read:

# /etc/restic/restic.env
cat > /etc/restic/restic.env <<'EOF'
RESTIC_REPOSITORY=s3:https://s3.example-provider.com/myserver-restic
RESTIC_PASSWORD_FILE=/etc/restic/password
AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY
RESTIC_CACHE_DIR=/var/cache/restic
EOF

chmod 600 /etc/restic/restic.env

What each line does:

  • RESTIC_REPOSITORY uses the s3:https://endpoint/bucket-name format described in the restic documentation. The s3: prefix tells restic to use its S3 backend. The example shown here (s3:https://s3.example-provider.com/myserver-restic) illustrates the general pattern, but the exact endpoint path style, region string, and TLS settings can differ between providers, so confirm the precise form in your provider’s own documentation before swapping in your real endpoint and bucket name.
  • RESTIC_PASSWORD_FILE points to the file from Step 3. This keeps the password itself out of the environment file and out of process listings.
  • AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY hold your bucket credentials. restic uses these standard variable names for every S3-compatible provider, AWS included.
  • RESTIC_CACHE_DIR gives restic a fixed local cache location. In Step 10, the systemd unit runs as root (no User= directive is set) and uses CacheDirectory=restic, which causes systemd to create and own /var/cache/restic on each start, matching this path. If you later add a User= line to that unit, systemd creates the cache directory under that user’s own cache namespace instead, so you’d need to update RESTIC_CACHE_DIR or provision the directory yourself to keep the two in sync.

The file uses plain KEY=value lines with no export keyword on purpose. That’s the format systemd’s EnvironmentFile= expects. To load the file into your current root shell, use set -a, which exports every variable the file defines:

set -a
. /etc/restic/restic.env
set +a

Quick sanity check that the repository variable loaded (this prints the URL, not a secret):

echo "$RESTIC_REPOSITORY"
Root shell listing /etc/restic with the password and restic.env files, both readable only by root, then echo printing the S3 repository URL.

Step 5: Initialize the Encrypted Repository

restic init

Expected output:

created restic repository 3f2a9c1b7e at s3:https://s3.example-provider.com/myserver-restic

Please note that knowledge of your password is required to access
the repository. Losing your password means that your data is
irrecoverably lost.

restic has now written its repository structure and encryption keys into the bucket. You only run init once per repository. Run it again against the same bucket and restic refuses, which is what you want.

If this step fails, jump to the troubleshooting section. Init failures are almost always a wrong endpoint, a wrong bucket name, or a key with no permission on the bucket.

Output of restic init reporting the created repository at the S3 URL, followed by the warning that losing the password makes the data unrecoverable.

Step 6: Define What to Back Up and What to Skip

Back up the directories that would be painful to rebuild. Don’t back up the whole root filesystem. A typical server list looks like this:

  • /etc: system and service configuration
  • /home and /root: user data and admin scripts
  • /var/www, /srv, /opt: application data, depending on your setup

Create an exclude file for the noise inside those trees:

# /etc/restic/excludes.txt
cat > /etc/restic/excludes.txt <<'EOF'
/home/*/.cache
/root/.cache
*.tmp
node_modules
EOF

Tip: Don’t rely on file-level backups of live database files (MySQL/MariaDB, PostgreSQL data directories). Copying them while the database runs can produce an inconsistent copy. Dump the database to a file first, for example in an ExecStartPre= step, and let restic back up the dump. For example, add one of these lines to the service unit in Step 10, and add /var/backups to the backup paths:

# MySQL/MariaDB (InnoDB): consistent dump without locking tables
ExecStartPre=/bin/sh -c 'mkdir -p /var/backups && mysqldump --single-transaction --all-databases > /var/backups/mysql-all.sql'
# PostgreSQL: dump all databases as the postgres user
ExecStartPre=/bin/sh -c 'mkdir -p /var/backups && runuser -u postgres -- pg_dumpall > /var/backups/postgres-all.sql'

If the dump fails, the ExecStartPre= step fails and systemd skips the backup, so the failure shows up in the service status instead of silently leaving you without database data.

Step 7: Run Your First Backup

# --exclude-file reads exclude patterns from the file
# --one-file-system stops restic from crossing into other mounted filesystems
# --tag labels the snapshot so you can filter by it later
restic backup \
  --exclude-file=/etc/restic/excludes.txt \
  --one-file-system \
  --tag scheduled \
  /etc /home /root /var/www

The first run uploads everything, so expect it to take a while on large data sets or slow uplinks. When it finishes, you’ll see a summary along these lines. The example below is illustrative only — your own file counts, data size, and elapsed time will depend entirely on what’s on your server and how fast your connection is:

Files: 48213 new, 0 changed, 0 unmodified
Dirs: 6120 new, 0 changed, 0 unmodified
Added to the repository: 3.412 GiB (2.981 GiB stored)

processed 48213 files, 3.618 GiB in 9:42
snapshot 9b7d4e21 saved

Run the same command again right away. The second run should finish much faster and report almost everything as unmodified. That’s deduplication at work: restic only uploads what changed.

Summary of a first restic backup run showing new files and directories, data added to the repository, and the saved snapshot ID.

Step 8: List Snapshots and Check Repository Integrity

List every snapshot in the repository:

restic snapshots

Expected output (illustrative — your snapshot IDs, host name, and timestamps will differ):

ID Time Host Tags Paths
———————————————————————
9b7d4e21 2026-10-25 10:31:04 myserver scheduled /etc
/home
/root
/var/www
c41a08f5 2026-10-25 10:42:17 myserver scheduled /etc
/home
/root
/var/www
———————————————————————
2 snapshots

Then verify the repository’s internal structure:

restic check

A healthy repository ends with:

no errors were found

By default, restic check verifies the repository’s structure and metadata. It doesn’t download and verify every data blob. To also read back a sample of the stored data, use --read-data-subset:

# Downloads and verifies a randomly chosen 5% of the pack files
restic check --read-data-subset=5%

A percentage picks a new random subset on each run, so repeated runs don’t guarantee that every pack file eventually gets checked. If you want systematic coverage, use the n/t form instead: restic divides the pack files into t groups and checks group n, so running --read-data-subset=1/5 through --read-data-subset=5/5 on successive runs reads the whole repository once.

This costs download bandwidth, and some providers bill for egress. Run it weekly or monthly, not every night.

Output of `restic snapshots` showing a table with two snapshots, followed by `restic check` ending in "no errors were found"

Step 9: Do a Test Restore to a Scratch Directory

This step turns “backup succeeded” into “I can actually get my data back.” Restore into a scratch directory, never over the live system:

mkdir -p /tmp/restore-test

# latest = the most recent snapshot
# --target is where the files are written
# --include limits the restore to one path inside the snapshot
restic restore latest --host "$(hostname)" --target /tmp/restore-test --include /etc/ssh

--host matters if more than one server backs up to the same repository: without it, latest means the newest snapshot from any host. Run restic snapshots first if you want to pick a specific snapshot ID instead.

Expected output (illustrative — your snapshot ID and timestamp will differ):

restoring snapshot c41a08f5 of [/etc /home /root /var/www] at 2026-10-25 10:42:17 to /tmp/restore-test

restic recreates the full original path under the target, so the files land in /tmp/restore-test/etc/ssh. Compare them with the live copy:

diff -r /etc/ssh /tmp/restore-test/etc/ssh && echo "Restore matches live data"

Expected output:

Restore matches live data

If diff reports differences, check whether the files changed after the snapshot was taken. Don’t assume a problem yet. Then clean up:

rm -rf /tmp/restore-test

Warning: Double-check that rm -rf path before you press Enter. Never restore with --target / while testing. That writes snapshot contents straight over your live system.

A few other commands help when you need one specific file:

# Browse what's inside this host's latest snapshot under /etc/nginx
restic ls latest --host "$(hostname)" /etc/nginx

# Search all snapshots for a filename
restic find nginx.conf
`restic restore latest --target /tmp/restore-test --include /etc/ssh` output, followed by the diff command printing "Restore matches live data"

Step 10: Schedule Backups with a systemd Service and Timer

systemd timers beat cron here for three reasons. Output goes to journald automatically. Persistent=true catches up on runs missed while the server was off. And the environment file loads cleanly through EnvironmentFile=. For more on how these units work, see the Oracle Linux systemd timer documentation.

Create the service unit. Adjust the restic path to match command -v restic from Step 1:

# /etc/systemd/system/restic-backup.service
[Unit]
Description=restic backup to S3-compatible storage
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
EnvironmentFile=/etc/restic/restic.env
# This unit has no User= directive, so it runs as root. On that condition,
# systemd's CacheDirectory=restic creates and owns /var/cache/restic on every
# start, matching RESTIC_CACHE_DIR above. If you add a User= line later,
# update RESTIC_CACHE_DIR (or pre-create the directory yourself) to match
# the path systemd actually creates for that user.
CacheDirectory=restic
# Run at low CPU and I/O priority so the backup doesn't starve services
Nice=10
IOSchedulingClass=idle
ExecStart=/usr/bin/restic backup --exclude-file=/etc/restic/excludes.txt --one-file-system --tag scheduled /etc /home /root /var/www
# Runs only if the backup succeeded
ExecStartPost=/usr/bin/restic forget --tag scheduled --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune

Then create the timer unit:

# /etc/systemd/system/restic-backup.timer
[Unit]
Description=Run restic backup nightly

[Timer]
# Every day at 02:30 local time
OnCalendar=*-*-* 02:30:00
# Spread start times so multiple servers don't hit storage at once
RandomizedDelaySec=30m
# Run a missed backup at next boot if the server was off at 02:30
Persistent=true

[Install]
WantedBy=timers.target

Reload systemd, enable the timer, and trigger one manual run. No point waiting until 02:30 to find out whether it works:

systemctl daemon-reload
systemctl enable --now restic-backup.timer
systemctl start restic-backup.service

systemctl start blocks until the oneshot service finishes. Check the result:

systemctl status restic-backup.service --no-pager
journalctl -u restic-backup.service -n 30 --no-pager

In the status output, look for status=0/SUCCESS. The journal should show the same snapshot ... saved line you saw in Step 7, followed by the forget/prune output. If the journal instead shows restic failing to read or write its cache, confirm with systemctl show restic-backup.service -p CacheDirectory and ls -ld /var/cache/restic that the directory systemd created matches RESTIC_CACHE_DIR in the environment file, and adjust one or the other accordingly.

Confirm the timer is scheduled:

systemctl list-timers restic-backup.timer

Expected output (dates will differ):

NEXT LEFT LAST PASSED UNIT ACTIVATES
Mon 2026-10-26 02:47:13 UTC 15h left Sun 2026-10-25 11:05:40 UTC 2min ago restic-backup.timer restic-backup.service

If you edit either unit later, rerun systemctl daemon-reload so the change takes effect.

systemctl list-timers showing the next and last restic-backup.timer runs, followed by journalctl output of a successful restic backup service run.

Step 11: Verify the Retention Policy Before Trusting It

The ExecStartPost= line applies the retention policy after each successful backup. The two commands split the work:

  • forget removes snapshot references that fall outside your keep rules.
  • prune, triggered here by the --prune flag, deletes the now-unreferenced data and reclaims storage.

Run forget without pruning and the snapshot list shrinks, but your bucket doesn’t.

Preview what the policy would remove before it ever deletes anything:

set -a; . /etc/restic/restic.env; set +a

# --dry-run shows which snapshots would be kept or removed, without changing anything
restic forget --tag scheduled --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --dry-run

The output groups snapshots under keep and remove headings. With only a day of snapshots, everything is kept. Re-run the preview after a couple of weeks to watch the policy start trimming.

Warning: forget with --prune permanently deletes backup data. Always preview a new or changed policy with --dry-run first. Flag names can change between restic versions, so confirm them with restic forget --help on your installed version.

Configuration

Key Environment Variables

VariableRequiredPurpose
RESTIC_REPOSITORYYesRepository URL, e.g. s3:https://endpoint/bucket-name. The exact format (path style, region, TLS) can vary by provider, so confirm it against your provider’s own documentation
RESTIC_PASSWORD_FILEYes (or RESTIC_PASSWORD)Path to the file holding the encryption password. Preferred over putting the password inline
AWS_ACCESS_KEY_IDYesS3 access key, for any S3-compatible provider
AWS_SECRET_ACCESS_KEYYesS3 secret key
RESTIC_CACHE_DIRNoLocal metadata cache location. Speeds up repeated runs. Under the systemd unit in Step 10, this must stay in sync with whatever directory CacheDirectory= actually creates for the user the service runs as

Retention Policy Patterns

Use caseExample keep rulesNotes
Small homelab server--keep-daily 7 --keep-weekly 4 --keep-monthly 6About six months of history with modest storage growth
Production config server--keep-daily 14 --keep-weekly 8 --keep-monthly 12Longer window to catch slowly noticed mistakes
Frequent (hourly) backups--keep-hourly 24 --keep-daily 7 --keep-weekly 4Change OnCalendar=hourly in the timer

Deduplication shares unchanged data across snapshots, so keeping more snapshots usually costs less than you’d expect. The exact amount depends on how much your data changes.

Hardening Credentials

  • Keep /etc/restic at 700 and every file in it at 600, owned by root.
  • Scope the S3 key to the restic bucket only, if your provider supports it.
  • If your provider offers object versioning or object lock, consider enabling it on the bucket. Otherwise a compromised server could use the same keys to delete the backups. Behavior varies by provider, so read their docs before turning it on.
  • Store the repository password off-server, separately from the S3 keys.

Splitting Out Heavier Jobs

Running prune and check --read-data-subset every night is more work than a typical server needs. A common pattern is a second service/timer pair, for example restic-maintenance.service on OnCalendar=weekly, that runs restic check --read-data-subset=5%. Point the second service at the same EnvironmentFile=.

Tips and Troubleshooting

Quick Fixes

  • Load the env file into your shell (set -a; . /etc/restic/restic.env; set +a) before running restic by hand.
  • Run manual commands as root. A permission error on /etc/restic/password usually means you aren’t root.
  • Read journalctl -u restic-backup.service before changing anything. restic’s error messages are specific.

“Repository does not exist” or restic init Fails

Why it happens: The bucket doesn’t exist yet, the endpoint or bucket name in RESTIC_REPOSITORY is wrong, or the access key has no permission on that bucket.

Fix:

  • Confirm in your provider’s console that the bucket exists, and copy its exact name.
  • Re-check the URL format: s3:https://ENDPOINT/BUCKET, with no trailing path you didn’t intend.
  • Confirm the access key is allowed to list, read, and write objects in that bucket.

Authentication or Access Denied Errors

Why it happens: AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY is missing, revoked, or pasted wrong. Another common cause is putting the S3 secret where the restic password belongs, or the reverse.

Fix: Reopen /etc/restic/restic.env and check both S3 values against the provider console. Remember the split: the S3 keys open the bucket, and /etc/restic/password decrypts the repository. Re-source the file after editing it.

Wrong Region or Endpoint Errors

Why it happens: The endpoint belongs to a different region than the bucket.

Fix: Copy the endpoint from your provider’s bucket details. On Scaleway it’s under Bucket settings > Bucket Information. Update RESTIC_REPOSITORY, then rerun restic snapshots to confirm restic connects.

Backup or Prune Fails with a Lock Error

Why it happens: restic locks the repository during operations. A crash, a killed process, or a power loss can leave a stale lock behind. A UPS Battery Backup on the server avoids the power-loss case. The error says the repository is already locked and names the host and PID holding the lock.

Fix:

  • Make sure no restic process is actually running against this repository, on this host or any other host that uses it. These commands only check the local machine:
pgrep -a restic
systemctl status restic-backup.service --no-pager

The lock error names the host and PID that hold the lock. If that’s a different server, log in there and run the same checks before you go further.

  • Only when nothing is running, clear the stale lock:
restic unlock

Warning: Never run restic unlock while another backup or prune is still active. Removing a live lock can let two operations modify the repository at once.

Storage Usage Keeps Growing

Why it happens: forget runs without --prune, or the retention policy never runs at all.

Fix: Confirm the ExecStartPost= line includes --prune, and check the journal for its output. To reclaim space right away, run restic prune by hand.

Backup “Succeeds” but Some Files Are Missing

Why it happens: restic can create a snapshot even when it couldn’t read some files, such as files deleted mid-run or files with permission problems. restic’s scripting documentation lists exit code 3 for the case where backup could not read some source data. systemd treats any non-zero exit as a failure, so the service shows as failed and the ExecStartPost= forget/prune step doesn’t run, even if the journal shows a snapshot ... saved line.

Fix: Read the journal for the unreadable paths. Exclude the expected ones (temp files, sockets) and fix permissions on the rest. Then repeat the test restore from Step 9.

Lost Repository Password

Why it happens: The password file was deleted, or the server was lost and no off-server copy existed.

Fix: There isn’t one. The encryption works as advertised, which is exactly why Step 3 tells you to store a copy elsewhere before your first backup.

Tips

  • Run a test restore every month or so. Restore a different directory each time. Now and then, restore a full snapshot onto a spare VM or a Raspberry Pi to rehearse a real recovery.
  • Back up to a second target too. A local copy on a NAS drive or external USB drive, alongside the S3 copy, gives you fast local restores plus off-site protection.
  • Filter by host. If several servers share one repository, restic snapshots --host myserver narrows the list to one machine.

Wrapping Up

Your server now pushes encrypted, deduplicated snapshots to S3-compatible storage every night. Old snapshots expire on schedule, and your test restore in Step 9 showed you can get the data back. My take: restic’s CLI-only design and strict password model feel unforgiving at first. But the whole setup is a few short files under /etc and /etc/systemd, so it’s easy to audit and copy to your next server. The test restore is the step that gets skipped, so put a recurring calendar reminder on it.

StepActionApplies To
1Install restic, check restic versionEvery server
2–4Create bucket and keys; store password and env file at 600Once per repository
5restic initOnce per repository
6–7Define paths and excludes; first restic backupEvery server
8restic snapshots and restic checkOngoing verification
9Test restore to /tmp/restore-testMonthly, at minimum
10–11systemd service and timer with forget --pruneEvery server

Resources

Sources retrieved 2026-10-25.