Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

BorgBackup for Linux Servers

By Kokil Thapa | Last reviewed: September 2026

Production Linux servers fail in predictable ways. Disks die, packages break during upgrades, and a mistyped rm -rf can erase a live site in seconds. BorgBackup for Linux servers solves that with encrypted, deduplicated snapshots you can verify and restore quickly. I rely on Borg on Ubuntu hosts that run Linux system administration workloads for clients in Nepal and abroad. This guide walks through install, repository setup, automation, and recovery—the same pattern I use before touching production Laravel or WordPress deployments.

What is BorgBackup and why should Linux server admins use it?

BorgBackup is a free, open-source backup tool built for Unix-like systems. It chunks files, deduplicates identical data across archives, compresses the result, and encrypts everything at rest. That design cuts storage use sharply compared with naive full copies.

On a real client project running multiple legal-tech portals on one EC2 instance, daily tarballs consumed disk space within weeks. Switching to Borg dropped backup size because shared Blade templates and uploaded PDFs deduplicated across sites. The same pattern applies to Ubuntu server backup strategies for any multi-app host.

BorgBackup for Linux Servers — Data FlowSource/var/www/etc /homeChunkingSHA-256 hashdedup matchCompresslz4 or zstdsmall footprintEncryptrepokey AESat restBorg Repository (local disk, NFS, or SSH remote)Archives: hostname-2026-09-12-0200Prune keeps daily / weekly / monthly retentionborg list · borg extract · borg mount FUSE
How BorgBackup for Linux servers chunks, deduplicates, compresses, and encrypts data before writing archives to a repository.

Borg fits servers that need point-in-time recovery without paying for enterprise backup appliances. It works on Ubuntu 22.04 and 24.04, Debian, Rocky Linux, and other distros with packages or pip installs. Pair it with off-site sync for a practical 3-2-1 approach described in our automated server backups complete setup article.

Key strengths for web hosts include incremental speed, integrity checks via authenticated encryption, and mountable archives through FUSE. Weaknesses matter too: Borg is file-level, not a block-level VM snapshot tool. Database consistency still needs logical dumps alongside file backups.

Core BorgBackup concepts

  • Repository — a directory or remote path holding all archives and deduplicated chunks.
  • Archive — a named snapshot created by borg create, such as web01-2026-09-12.
  • Passphrase — unlocks encrypted repos; store it outside the server you back up.
  • Prune — deletes old archives by retention rules without breaking deduplication.
  • Compact — reclaims space after pruning removes unreferenced chunks.

How do you install BorgBackup on Ubuntu and Debian Linux servers?

Install Borg from your distribution package manager when possible. Pin a known version on production boxes so automation scripts do not break silently after an unattended upgrade.

Package install on Ubuntu 24.04

sudo apt update
sudo apt install -y borgbackup borgbackup-fuse
borg --version

Ubuntu 22.04 and Debian 12 ship Borg 1.2.x in their repos. That release line is stable for daily server backups. If you need a newer feature, use pip inside a virtualenv rather than mixing system Python packages blindly.

Optional pip install in a virtualenv

sudo apt install -y python3-venv python3-dev libssl-dev liblz4-dev libzstd-dev
python3 -m venv /opt/borg-venv
/opt/borg-venv/bin/pip install --upgrade pip borgbackup
ln -sf /opt/borg-venv/bin/borg /usr/local/bin/borg
borg --version

After install, confirm FUSE support if you plan to browse archives with borg mount. The borgbackup-fuse package on Debian-family systems provides the helper. On headless servers, FUSE is optional because borg extract handles most restores.

Before your first backup, read the official install notes at BorgBackup installation documentation. They list platform-specific dependencies that prevent cryptic compile errors on minimal cloud images.

How do you create and configure an encrypted BorgBackup repository?

Repository creation is a one-time step per backup destination. Choose encryption mode carefully. repokey-blake2 is the common default: the key material lives inside the repo, and your passphrase unlocks it.

Initialize a local repository

sudo mkdir -p /backup/borg-repos/web01
sudo chown root:root /backup/borg-repos/web01
sudo chmod 700 /backup/borg-repos/web01

export BORG_PASSPHRASE='use-a-long-random-passphrase'
export BORG_RSH='ssh -i /root/.ssh/backup_key'

sudo borg init --encryption=repokey-blake2 /backup/borg-repos/web01

Generate passphrases with a local tool like the password generator and store them in a password manager or sealed envelope. Never commit passphrases to Git. On sister sites I maintain with Deployer 7 and GitLab CI, backup credentials live in root-only env files outside the web root.

Create your first archive

export BORG_PASSPHRASE='use-a-long-random-passphrase'
export BORG_REPO='/backup/borg-repos/web01'

sudo borg create \
  --verbose \
  --stats \
  --compression lz4 \
  --exclude-caches \
  --exclude '/var/www/*/storage/logs/*' \
  --exclude '/var/www/*/node_modules' \
  --exclude '/tmp/*' \
  ::'{hostname}-{now:%Y-%m-%d-%H%M}' \
  /etc \
  /var/www \
  /home/deploy

The {hostname} and {now} placeholders expand at runtime. Exclusions matter on Laravel apps: skip node_modules, cache dirs, and session temp paths you can rebuild. Keep .env files backed up—they hold database credentials your restore depends on.

BorgBackup Workflow on Linux1. borg initonce per repo2. borg createdaily snapshot3. borg pruneretention rules4. checkverifyAutomate via systemd timer or cron + log to journaldExport BORG_PASSPHRASE from /root/.borg-env (chmod 600)Local repo/backup on same VPSRemote repouser@backup:/repos/hostTest restore monthly — untested backups are wishful thinking
Standard BorgBackup for Linux servers workflow: initialize once, create daily archives, prune by policy, then verify with check and test restores.

Remote repository over SSH

Off-site copies protect against datacenter loss or ransomware that encrypts local disks. Point Borg at a dedicated backup user on another VPS or NAS.

export BORG_REPO='ssh://borg@backup.example.com:22/~/repos/web01'
export BORG_RSH='ssh -i /root/.ssh/borg_backup -o StrictHostKeyChecking=accept-new'

borg init --encryption=repokey-blake2 $BORG_REPO
borg create --stats $BORG_REPO::'{hostname}-{now}' /var/www /etc

Harden the backup SSH account: key-only auth, no shell beyond borg serve, and firewall rules limiting source IPs. Our SSH hardening guide covers the same principles you should apply to backup traffic.

Prune and compact on a schedule

borg prune \
  --verbose \
  --list \
  --keep-daily=7 \
  --keep-weekly=4 \
  --keep-monthly=6 \
  $BORG_REPO

borg compact $BORG_REPO

Prune rules should match your recovery objectives. Seven dailies plus four weeklies gives roughly five weeks of granular rollback. Monthly archives stretch retention without unbounded disk growth. Run borg compact after prune on busy repos to reclaim chunk storage.

How do you automate BorgBackup with systemd timers on Linux?

Cron works, but systemd timers give you journald logs, dependency ordering, and failure notifications. I prefer timers on Ubuntu servers that already use systemd for PHP-FPM and queue workers.

Store secrets safely

sudo install -m 600 /dev/null /root/.borg-env
sudo nano /root/.borg-env

File contents:

BORG_PASSPHRASE=your-long-passphrase-here
BORG_REPO=/backup/borg-repos/web01
BORG_RSH=ssh -i /root/.ssh/borg_backup

Backup script at /usr/local/bin/borg-backup.sh

#!/bin/bash
set -euo pipefail
source /root/.borg-env

LOG_PREFIX="[borg-backup]"

echo "$LOG_PREFIX starting $(date -Is)"

borg create \
  --stats \
  --compression lz4 \
  --exclude-caches \
  ::'{hostname}-{now:%Y-%m-%d-%H%M}' \
  /etc /var/www /home/deploy

borg prune \
  --keep-daily=7 \
  --keep-weekly=4 \
  --keep-monthly=6

borg compact
borg check --verify-data

echo "$LOG_PREFIX finished $(date -Is)"
sudo chmod 750 /usr/local/bin/borg-backup.sh

Wire the script into systemd following our systemd service management guide. Create a service unit and a daily timer. Enable the timer with systemctl enable --now borg-backup.timer.

Database files need separate handling. MySQL and PostgreSQL must be dumped before Borg reads data directories, or you risk inconsistent pages on restore. Automate logical dumps first, then include the dump directory in your Borg path list. See automate database backups on Linux for mysqldump and pg_dump patterns that pair well with Borg.

Monitoring backup success

Check timer status weekly:

systemctl list-timers borg-backup.timer
journalctl -u borg-backup.service --since "7 days ago"

Integrate alerts with your existing stack. Netdata, Nagios, or a simple cron mail to root all work. A silent failed backup is worse than no backup—you assume protection that does not exist. Combine this with broader monitoring from our Netdata monitoring guide.

BorgBackup vs rsync: which backup approach fits Linux servers best?

Teams often compare Borg with rsync or rclone mirror jobs. Each tool solves a different layer of the backup problem. Borg excels at versioned, encrypted history. Rsync excels at live directory sync to a warm standby.

CriteriaBorgBackuprsync / rclone mirror
Version historyNative named archives with retentionNeeds separate snapshot dir or flags
DeduplicationContent-defined across all archivesNone unless filesystem snapshots
Encryption at restBuilt-in authenticated encryptionRequires LUKS, gpg, or remote trust
Restore granularitySingle file from any archiveOverwrites target; rollback is manual
Operational complexityModerate; learn prune and checkLow for simple mirror jobs
Best fitLong-term server file historyReal-time sync to second server

Many production setups use both. Borg holds encrypted history; rsync keeps a near-live copy on a secondary VPS. Our rsync vs rclone comparison covers transport details when off-site sync is the bottleneck.

3-2-1 Backup with BorgBackupProductionUbuntu web serverLaravel / WordPressCopy 1Local Borg reposame datacenter diskCopy 2SSH remote Borgdifferent region VPS3 copies · 2 media types · 1 off-siteAdd DB dumps + config outside the app treeRansomware riskimmutable off-site copyProvider outagecross-region restoreHuman errorpoint-in-time archive
A practical 3-2-1 backup layout using BorgBackup for Linux servers with local and remote encrypted repositories.

For Nepal-based businesses on budget VPS plans, a second small instance in another region costs roughly Rs 1,500–3,000/month (~USD 11–22). That is cheap insurance compared with rebuilding a booking portal or law-firm client document store from scratch.

How do you restore files and full sites from BorgBackup archives?

Restores fail in production when nobody has practiced them. Schedule a monthly restore drill to a staging directory. Document the exact commands your team runs at 2 a.m. when the homepage is down.

List and inspect archives

source /root/.borg-env
borg list $BORG_REPO
borg list $BORG_REPO::web01-2026-09-11-0200 --short

Extract a single file

borg extract --verbose $BORG_REPO::web01-2026-09-11-0200 \
  var/www/example.com/.env

Borg recreates the path relative to your current working directory. Change into / or a temp folder before extracting to avoid cluttering the wrong location.

Mount an archive read-only with FUSE

mkdir -p /mnt/borg-mount
borg mount $BORG_REPO::web01-2026-09-11-0200 /mnt/borg-mount
ls /mnt/borg-mount/var/www/
borg umount /mnt/borg-mount

FUSE mounts are handy for comparing two versions or copying a handful of files. Unmount cleanly before running the next backup job.

Full site recovery outline

  1. Provision a clean Ubuntu server using our Ubuntu server setup guide.
  2. Install Borg and restore /etc, web roots, and home directories from the latest archive.
  3. Restore database dumps from the same backup window—not live datadir copies.
  4. Fix ownership: chown -R www-data:www-data /var/www/site per Linux file permissions conventions.
  5. Reload PHP-FPM and verify TLS certs still match the hostname.
  6. Run application smoke tests before switching DNS.

On legal-tech portals I have shipped, document uploads live under storage/app. Confirm Spatie Media Library paths restore completely before you announce recovery to the client. Partial restores erode trust faster than brief downtime.

BorgBackup Restore PathsWhat failed?Single file lostborg extract one pathCompare versionsborg mount FUSE browseFull server lossnew VPS + full extractPost-restore checklistRestore DB dump · fix permissions · reload servicesRun borg check · update DNS · notify stakeholders
Restore decision tree for BorgBackup on Linux servers: extract for one file, mount to compare, full extract after hardware loss.

Integrity verification

Run borg check --verify-data quarterly on repos that matter. It reads chunks and confirms checksums. The command takes time on large repos, so schedule it off-peak. Official guidance lives at BorgBackup quick start documentation.

What security and permission practices protect BorgBackup repositories?

Backups contain everything attackers want: database credentials, API keys, client documents, and TLS private keys. Treat repos as crown jewels.

  • Restrict repo directories to root or a dedicated borg user with mode 700.
  • Never store passphrases on the same volume as the only repo copy.
  • Use separate SSH keys for backup traffic; rotate them yearly.
  • Block backup server inbound SSH except from known production IPs.
  • Align with broader hardening from Ubuntu web server hardening and server security in Nepal.

Ransomware actors hunt backup paths. Hide repo locations, disable web-served directories under /backup, and keep an off-site copy an attacker cannot reach from the compromised app user. Read the project security notes at borgbackup.org for encryption model details.

When clients need ongoing backup monitoring and restore support, that falls under support and maintenance services rather than a one-time install. Sites like Adventure Third Pole Trek depend on nightly data safety because bookings and supplier records cannot be recreated from memory.

Key Takeaways

  • Initialize one encrypted Borg repo per server or logical site group, then schedule daily borg create with explicit exclusions.
  • Pair file backups with logical database dumps so MySQL and PostgreSQL restore cleanly.
  • Automate prune, compact, and check via systemd timers; alert on failure instead of assuming success.
  • Keep a remote SSH repo in another region for true off-site recovery against disk or datacenter loss.
  • Run a monthly test restore to staging and document commands before an emergency.
  • Lock down repo permissions and passphrases—the backup is as sensitive as production itself.

People Also Ask

Does BorgBackup work with Laravel and WordPress file layouts?

Yes. Include /var/www, custom Nginx or Apache configs under /etc, and deployment user home dirs. Exclude cache, node_modules, and regenerable log files. Always back up .env and upload directories. WordPress sites on PHP 8.3+ hosts follow the same pattern with wp-content/uploads as a critical path.

Can BorgBackup run on low-memory VPS instances?

Borg runs fine on 1–2 GB RAM VPS plans common for small business sites in Nepal. Large first backups may spike CPU and I/O. Schedule jobs during off-peak hours. Enable lz4 compression for speed over maximum ratio on constrained boxes.

How much disk space do Borg archives consume?

Deduplication makes steady-state growth slower than raw data size. A site changing 200 MB daily might add far less after dedup. Monitor repo size with borg info. Plan headroom for retention windows and compact cycles.

Is BorgBackup enough for full disaster recovery?

Borg covers file-level recovery well. It does not replace infrastructure-as-code, DNS documentation, or database replication. Combine Borg with documented rebuild steps, secondary servers, and provider snapshots for complete coverage.

Build reliable backups before you need them

BorgBackup for Linux servers gives you encrypted history, efficient storage, and fast file-level recovery without proprietary agents. Install it early, automate prune and check, push archives off-site, and prove restores on a schedule. That is the difference between a bad afternoon and a lost business.

Need help designing backup strategy for a production Laravel stack, WooCommerce store, or multi-site EC2 host? Review our Linux administration services, browse the portfolio for deployed examples, or contact us to audit your current setup before the next outage finds the gaps.

Frequently Asked Questions

BorgBackup is a free, open-source tool that stores encrypted, deduplicated file snapshots in a repository. Linux admins use it for point-in-time recovery without enterprise backup appliances.

On Ubuntu 24.04, run apt update and apt install borgbackup borgbackup-fuse, then confirm with borg --version. Ubuntu 22.04 and Debian 12 ship Borg 1.2.x from their repos, which is stable for daily server backups. Pin a known version on production boxes so automation does not break after unattended upgrades. If you need newer features, install borgbackup inside a Python virtualenv at /opt/borg-venv and symlink borg to /usr/local/bin. Install borgbackup-fuse only if you plan to browse archives with borg mount; headless servers can rely on borg extract alone.

A second small VPS in another region typically costs Rs 1,500–3,000/month (~USD 11–22)—cheap insurance against datacenter loss.

Create a root-owned directory with mode 700, set BORG_PASSPHRASE and BORG_RSH, then run borg init --encryption=repokey-blake2 on the local path or SSH remote URL. Generate a long random passphrase with a password manager and never commit it to Git. On production hosts I maintain with Deployer 7, credentials live in root-only env files outside the web root. After init, run borg create with --compression lz4, --exclude-caches, and paths such as /etc, /var/www, and /home/deploy. Use placeholders like {hostname}-{now:%Y-%m-%d-%H%M} so each archive is uniquely named at runtime.

Borg excels at versioned, encrypted history with native deduplication and named archives you can prune by policy. Rsync excels at live directory sync to a warm standby but lacks built-in encryption and meaningful rollback unless you add separate snapshot directories. Many production setups use both: Borg holds encrypted long-term history while rsync keeps a near-live copy on a secondary VPS. Choose Borg when you need granular file recovery from any past date without overwriting the target. Choose rsync when the priority is real-time mirroring, not retention rules and integrity checks.

Store BORG_PASSPHRASE, BORG_REPO, and BORG_RSH in /root/.borg-env with mode 600. Write a script at /usr/local/bin/borg-backup.sh that sources that file, runs borg create with exclusions, borg prune with your retention flags, borg compact, and borg check --verify-data. Wire it into a systemd service and daily timer, then enable with systemctl enable --now borg-backup.timer. I prefer timers over cron on Ubuntu because journald captures logs and dependencies order cleanly alongside PHP-FPM and queue workers. Check weekly with systemctl list-timers and journalctl -u borg-backup.service. Alert on failure—a silent failed backup is worse than no backup.

Source /root/.borg-env, list archives with borg list $BORG_REPO, then run borg extract --verbose against the named archive and the file path such as var/www/example.com/.env. Borg recreates paths relative to your current working directory, so cd to / or a temp folder before extracting to avoid writing files into the wrong location. For comparing versions without a full extract, mkdir a mount point and use borg mount read-only, then borg umount when finished. Schedule a monthly restore drill to staging and document the exact commands before an emergency at 2 a.m.

Not if you only copy live data directories. Borg is file-level, so reading MySQL or PostgreSQL datadir files while databases are running risks inconsistent pages on restore. Automate logical dumps with mysqldump or pg_dump first, then include the dump directory in your Borg path list during the same backup window. On restore, replay those dumps rather than dropping raw datadir copies back onto a clean server. This pairing is the same pattern I use before touching production Laravel or WordPress deployments where database integrity matters as much as web roots and .env files.

Exclude node_modules, cache directories, regenerable log paths such as /var/www//storage/logs/, and /tmp/*. Use --exclude-caches and explicit --exclude flags in your borg create command. Session temp paths and compiled assets you can rebuild belong off the backup set. Do not exclude .env files—they hold database credentials your restore depends on. On legal-tech portals, document uploads under storage/app must stay included. Spatie Media Library paths in particular need to restore completely before you tell a client recovery is done. Partial restores erode trust faster than brief downtime.

Use Borg for encrypted, deduplicated file-level history on Ubuntu web hosts; use VM snapshots when you need full-disk imaging of entire machines.

Point BORG_REPO at ssh://borg@backup.example.com:22/~/repos/web01 and set BORG_RSH to use a dedicated key with StrictHostKeyChecking=accept-new. Run borg init --encryption=repokey-blake2 against that URL, then borg create with the same env vars you use locally. Harden the backup account with key-only auth, restrict the shell to borg serve, and firewall inbound SSH to known production IPs. Off-site copies protect against datacenter loss and ransomware that encrypts local disks. This gives you a practical 3-2-1 layout: production data, local encrypted repo, and remote encrypted repo in another region.

A practical starting point is --keep-daily=7, --keep-weekly=4, and --keep-monthly=6, which yields roughly five weeks of granular daily rollback plus six monthly checkpoints. Match prune rules to your recovery objectives rather than copying defaults blindly. Seven dailies plus four weeklies covers most mistaken deletes and bad deploys. Monthly archives stretch retention without unbounded disk growth from deduplicated chunks. Always run borg compact after prune on busy repos to reclaim space from unreferenced chunks. Review disk use quarterly and adjust if backup volume grows faster than expected.

Run borg check --verify-data on repos that matter, scheduled quarterly and off-peak because it reads all chunks and confirms checksums. Include check in your automated backup script for lighter routine validation, but expect full verify-data passes to take significant time on large web-host repos. Pair checks with monthly test restores to a staging directory so you confirm both chunk integrity and practical recoverability. Official guidance lives in the BorgBackup quick start documentation. A repo that passes create jobs but fails check is a ticking problem—treat verification failures as urgently as a failed backup timer.

Restrict repo directories to root or a dedicated borg user with mode 700. Store passphrases in a password manager or sealed envelope, never on the same volume as your only repo copy and never in Git. Use separate SSH keys for backup traffic and rotate them yearly. Block backup-server inbound SSH except from known production IPs. Ransomware actors hunt backup paths, so hide repo locations and keep web servers from serving anything under /backup. Backups contain database credentials, API keys, client documents, and TLS private keys—treat repos as crown jewels comparable to production itself.

Yes. Include /var/www, Nginx or Apache configs under /etc, and deployment user home directories such as /home/deploy in your archive paths. Exclude cache, node_modules, and regenerable logs, but always back up .env files. WordPress uploads and Laravel storage paths must stay in scope. After a full site recovery, fix ownership with chown -R www-data:www-data on web roots, restore database dumps from the same backup window, reload PHP-FPM, verify TLS certs match the hostname, and run smoke tests before switching DNS. On multi-app EC2 hosts running several legal-tech portals, Borg deduplication sharply cuts backup size when shared templates and uploaded PDFs repeat across sites.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: