How to Automate Raspberry Pi Backups to a UniFi NAS

Management Summary
Automatic backups protect selected Raspberry Pi application data by regularly copying it to a UniFi NAS, a storage device on the local network. Keeping a second copy helps recover from lost or damaged data without relying on a manual routine every day. The article explains how files and databases become a usable backup. This is not a complete copy of the computer: recovery still needs testing, and a separate offline or off-site copy protects against failures affecting both devices.
Jump to the interactive example ↓
Contents
A daily backup on a UniFi UNAS Pro provides a second copy of Raspberry Pi application data. This example saves selected directories and MySQL databases through SMB, the network file-sharing protocol. A NAS copy alone is not a complete recovery plan: restore tests and a separate offline or off-site copy remain necessary.
Prerequisites and scope
The example uses the Linux account pi, the home directory /home/pi, Bash and a MySQL-compatible dump client. Account names, numeric user/group IDs, database names and source directories must match the installation. Every source directory must be readable by the backup account. Copying the directory of a running Docker database with tar can mix files from different moments. The database may change one file while another is already being copied. A database export avoids treating these changing files as an ordinary folder.
1. NAS preparation
In UniFi Drive, a shared drive named Pi_Backups holds the backup files. A dedicated account needs write access to this share and File Services credentials for SMB. A UniFi console login is not necessarily an SMB login. The SMB service must be enabled; the exact labels depend on the installed Drive version.
2. SMB share connection
The package cifs-utils supplies the SMB mount helper. The following setup commands require administrative privileges:
sudo apt update
sudo apt install cifs-utils
sudo mkdir -p /mnt/unas_backup
The file /etc/.unas_creds, created with sudo nano /etc/.unas_creds, contains two lines:
username=backup_user
password=REPLACE_WITH_SMB_PASSWORD
The password remains plain text in this file. File permissions restrict access; a leading dot does not encrypt credentials. The file must belong to root:
sudo chown root:root /etc/.unas_creds
sudo chmod 600 /etc/.unas_creds
The following entry belongs in /etc/fstab. The address and share name are examples; UID and GID 1000 must correspond to the backup account, as checked with id pi. The NAS still enforces its own access permissions.
//192.168.1.XXX/Pi_Backups /mnt/unas_backup cifs credentials=/etc/.unas_creds,uid=1000,gid=1000,iocharset=utf8,_netdev,nofail 0 0
sudo mount /mnt/unas_backup tests this specific mount. With nofail, boot can continue without the NAS. A failed mount still prevents backups; after NAS recovery, mounting again is necessary. SMB does not automatically imply encrypted transport. Encryption requirements must be configured and checked separately.
3. Database access
The file /home/pi/.my.cnf belongs to the account running the job and contains the database credentials below. chmod 600 /home/pi/.my.cnf restricts access. The dedicated database account requires the privileges documented for the chosen dump options, including routines and events.
[client]
user=backup_user
password=REPLACE_WITH_DATABASE_PASSWORD
4. Backup script
The following script belongs in /home/pi/pi_backup.sh. Before use, app1 app2 and TARGET_FOLDERS must be replaced with the actual database and directory names. For MariaDB, the installed mariadb-dump client and its supported options need a separate check.
#!/bin/bash
set -euo pipefail
umask 077
PATH=/usr/local/bin:/usr/bin:/bin
NAS_MOUNT="/mnt/unas_backup"
TARGET_FOLDERS=(/var/www/html /etc/nginx)
DATABASES=(app1 app2)
exec 9>/home/pi/.pi-backup.lock
flock -n 9 || { echo "Backup already running" >&2; exit 1; }
mountpoint -q "$NAS_MOUNT" || { echo "NAS is not mounted" >&2; exit 1; }
[[ $(findmnt -n -o FSTYPE --target "$NAS_MOUNT") == cifs ]] || exit 1
BACKUP_ID=$(date +%Y-%m-%d_%H-%M-%S)
WORK_DIR="$NAS_MOUNT/.partial-$BACKUP_ID"
DEST_DIR="$NAS_MOUNT/$BACKUP_ID"
mkdir -- "$WORK_DIR"
trap 'echo "Backup failed; incomplete directory: $WORK_DIR" >&2' ERR
mysqldump --defaults-extra-file=/home/pi/.my.cnf --single-transaction --routines --events --triggers --databases "${DATABASES[@]}" | gzip > "$WORK_DIR/databases.sql.gz"
gzip -t "$WORK_DIR/databases.sql.gz"
tar -czf "$WORK_DIR/files.tar.gz" -- "${TARGET_FOLDERS[@]}"
tar -tzf "$WORK_DIR/files.tar.gz" > /dev/null
printf '%s\n' "$BACKUP_ID" > "$WORK_DIR/COMPLETE"
mv -- "$WORK_DIR" "$DEST_DIR"
echo "Backup written: $DEST_DIR"
pipefail exposes dump errors hidden by a successful gzip process. This straight-line script stops on a failed dump or file archive. An incomplete run keeps a .partial- directory; the final directory appears only after both archive checks succeed. These checks can detect damaged archive files. A readable archive can still lack a required database or configuration file. Only a restore test shows whether the application works with the saved data.
--single-transaction provides a consistent view for transactional tables such as InnoDB. This guarantee does not cover tables without transaction support or changes to the database structure during the export, such as adding a column. Those cases need a different backup strategy. Files copied afterward are not automatically synchronized with that database snapshot. Applications requiring consistency between uploads and database records need a coordinated maintenance window or suitable snapshot procedure.
5. Schedule and verification
After chmod +x /home/pi/pi_backup.sh, a manual run under the same account must succeed. The following entry in the pi account’s crontab -e starts the job at 02:00 in the cron service’s local timezone:
0 2 * * * /home/pi/pi_backup.sh >> /home/pi/backup_log.txt 2>&1
Each run adds lines to the same log. Regular rotation starts a new log file and removes older log files according to a separate retention rule, preventing unlimited growth. Monitoring must detect failed jobs and missing recent completed backups. The script deliberately performs no automatic deletion. A retention policy defines how long completed backups remain available. Before an old backup is deleted, the policy must account for free space, unfinished backups and the most recent backup that passed a restore test.

Questions and answers
Does this back up the entire Raspberry Pi?
No. The result contains the selected application databases and directories. Operating system installation, boot configuration, database accounts and any omitted services require a separately documented recovery procedure.
When is a backup usable?
Only a restore test on an isolated test system demonstrates recoverability. The test needs a compatible database version, imported SQL, extracted files and an application check. A gzip size check or a COMPLETE marker cannot replace that test.
Why is there no automatic cleanup?
Deleting old copies after an unverified run can destroy the last usable recovery point. Retention needs a separate policy that checks successful restores and available space.
Learn by trying
How far back would an outage take you?
Move the outage and change the backup interval. Compare the last saved state with the time you need to restore service.
Dots: successful backups. Orange: failed run. Red line: outage. Shaded area: time since the last saved state.
- Last saved state
- Time not covered by backups
- Assumed downtime
Simplified model: a verified backup exists at hour 0. Later backups capture and finish instantly at their scheduled time; an outage at that exact time occurs afterwards. Optionally, only the latest scheduled run after hour 0 fails. No log replication, backup duration, retention or data volume simulated. The interval represents potentially unsaved changes; restore duration is your assumption, not a measurement or an RTO/RPO commitment.
This module runs in your browser and does not send or store your input.
Learn by trying
One minute: can you spot the mistake?
Last valid backup: 23 hours ago. Restore duration: 2 hours. How much time’s worth of changes could be missing after restoring?
The saved state is 23 hours old. The two hours describe restoring service. Data age and downtime are different quantities; the number of affected changes depends on the workload.
Take a guess!
Explore
Take a guess!
Enter your estimate first. Then reveal the calculation, result and difference.
PNG with settings, result and article link. Created locally only when you click.
These exercises calculate in your browser. The learning module does not send your answers.
One decision, two consequences
Simplified learning model
One decision, two consequences
There is rarely just one right answer. Make a choice and compare its consequences.
These examples run only in your browser. No real systems are disrupted.
PNG with settings, result and article link. Created locally only when you click.
The technology face-off
Simplified learning model
The technology face-off
The same conditions, two approaches. Change the numbers and watch the comparison shift.
These examples run only in your browser. No real systems are disrupted.
PNG with settings, result and article link. Created locally only when you click.


