LW IT Solutions
«« Blog Overview « IT & Networks
This post in other languages:

Bulletproof Your Data: Automated Raspberry Pi Backups to Ubiquiti UNAS Pro

If you are running self-hosted services, home automation, or custom web applications on a Raspberry Pi, you already know its Achilles’ heel: the microSD card. SD cards are prone to corruption, especially with heavy database read/write cycles.

To build a truly resilient architecture, your data cannot live solely on the Pi. It needs to be offloaded to a redundant, enterprise-grade storage solution. In this guide, we will walk through setting up a fully automated, daily backup from a Raspberry Pi directly to a Ubiquiti UNAS Pro.

We will build a script that targets specific critical directories and performs a complete mysqldump of your databases, compressing everything neatly into daily archives.

Step 1: Prepare the UNAS Pro

Before the Raspberry Pi can send data, the UNAS Pro needs to be ready to receive it.

  1. Log into your UniFi OS console and open the Storage / NAS application.
  2. Create a new Shared Folder (e.g., Pi_Backups).
  3. Create a dedicated local user (e.g., backup_user) with a strong password.
  4. Assign this user Read/Write permissions specifically to the Pi_Backups folder.
  5. Ensure SMB (Server Message Block) is enabled for this share.

Step 2: Mount the UNAS Pro on the Raspberry Pi

We need the Raspberry Pi to treat the UNAS Pro network share as if it were a local physical drive. We will achieve this using cifs-utils.

1. SSH into your Raspberry Pi.

2. Install the necessary utilities:

    sudo apt update
    sudo apt install cifs-utils

    3. Create a local mount point:

    sudo mkdir -p /mnt/unas_backup

    4. Create a hidden credentials file so your UNAS Pro password isn’t exposed in plain text in the system configuration:

    sudo nano /etc/.unas_creds

    Add the following lines (replace with your UNAS Pro IP and user details):

    username=backup_user
    password=YourStrongPassword
    domain=WORKGROUP

    Secure the file:

    sudo chmod 600 /etc/.unas_creds

    5. Edit the /etc/fstab file to ensure the NAS mounts automatically on boot:

    sudo nano /etc/fstab

    Add this line to the bottom:

    //192.168.1.XXX/Pi_Backups /mnt/unas_backup cifs credentials=/etc/.unas_creds,uid=1000,gid=1000,iocharset=utf8 0 0

    6. Mount the drive to test it:

    sudo mount -a

    Step 3: Secure Your MySQL Credentials

    To allow our script to perform a mysqldump without prompting for a password (which would break automation), we need to store the database credentials securely.

    1. Create a MySQL configuration file for the root user:

      nano ~/.my.cnf

      2. Add your database credentials:

      [client]
      user=root
      password=YourDatabasePassword

      3. Secure the file:

      chmod 600 ~/.my.cnf

      Step 4: Write the Backup Script

      Now we will create the bash script that handles the heavy lifting: exporting the database, compressing specific folders, and cleaning up old backups to prevent your UNAS Pro from filling up completely.

      1. Create the script file:

        nano ~/pi_backup.sh

        2. Paste the following code. (Make sure to modify the TARGET_FOLDERS to point to the actual directories you want to back up, like /etc or /var/www):

        #!/bin/bash
        
        # Define variables
        BACKUP_DATE=$(date +"%Y-%m-%d")
        NAS_MOUNT="/mnt/unas_backup"
        DEST_DIR="$NAS_MOUNT/$BACKUP_DATE"
        
        # Define the folders you want to backup (separated by spaces)
        TARGET_FOLDERS="/var/www/html /etc/nginx /home/pi/docker-data"
        
        # Check if NAS is mounted before proceeding
        if ! mountpoint -q $NAS_MOUNT; then
            echo "Error: UNAS Pro is not mounted at $NAS_MOUNT"
            exit 1
        fi
        
        # Create today's backup directory
        mkdir -p "$DEST_DIR"
        
        # 1. Database Backup (mysqldump)
        echo "Starting MySQL backup..."
        mysqldump --all-databases | gzip > "$DEST_DIR/db_backup_$BACKUP_DATE.sql.gz"
        
        # 2. File/Folder Backup (tar compression)
        echo "Starting file backup..."
        tar -czf "$DEST_DIR/files_backup_$BACKUP_DATE.tar.gz" $TARGET_FOLDERS
        
        # 3. Cleanup: Remove backups older than 14 days
        echo "Cleaning up old backups..."
        find "$NAS_MOUNT" -mindepth 1 -maxdepth 1 -type d -mtime +14 -exec rm -rf {} \;
        
        echo "Backup completed successfully!"

        3. Make the script executable:

        chmod +x ~/pi_backup.sh

        Step 5: Automate with Cron

        The final piece of the architecture is scheduling the script to run automatically every single day. The middle of the night is usually best to avoid resource contention.

        1. Open the cron table:

          crontab -e

          2. Add the following line to the bottom to run the backup every day at 2:00 AM:

          0 2 * * * /home/pi/pi_backup.sh > /home/pi/backup_log.txt 2>&1

          Summary

          You have now successfully engineered a robust, automated disaster recovery plan. Every night at 2:00 AM, your Raspberry Pi will dump its entire database, compress your essential configuration and application folders, and securely transfer them over the network to your Ubiquiti UNAS Pro. Furthermore, it will automatically prune archives older than two weeks, ensuring your storage remains optimized.

          Lukas Wojcik

          Lukas Wojcik

          Systems architect and technology enthusiast specializing in scalable tracking solutions, GMP Stack (GA4 & GTM), and robust backend architectures. Advocate for clean code and privacy-first design.

          Leave a Reply

          Your email address will not be published. Required fields are marked *

          ALL ARTICLES & CATEGORIES

          Data Privacy

          Digital Analytics

          Digital Marketing

          IT & Networks

          Smart Home