Auto-Backup Your Raspberry Pi SD Card to a Network Share
Auto-Backup Your Raspberry Pi SD Card to a Network Share SD cards fail. Pi projects that took hours to configure vanish in an instant. Automated backups to a NAS or network share protect your work. Here's how to set it up. Strategy 1. Pi mounts a network share (NFS or SMB/Samba) 2. A cron job runs a compressed backup of the Pi's own SD card 3. Backup goes directly to the network share 4. Old backups rotate automatically (keep last 5) Step 1 — Mount a Network Share Samba (SMB) — for NAS/Windows shares sudo apt install cifs-utils -y sudo mkdir /mnt/backup Create credentials file: sudo nano /etc/samba/user username=yournasuser password=yournaspassword sudo chmod 600 /etc/samba/user Add to /etc/fstab: //192.168.1.100/backups /mnt/backup cifs credentials=/etc/samba/user,iocharset=utf8 0 0 Mount: sudo mount -a Verify: ls /mnt/backup should show NAS contents. Step 2 — Create Backup Script Save as /home/pi/backup.sh: bash #!/bin/bash BACKUPDIR="/mnt/backup/pi-backups" HOSTNAME=$(hostname) DATE=$(date +%Y%m%d%H%M) FILENAME="${HOSTNAME}${DATE}.img.gz" KEEP=5 Create backup directory mkdir -p "$BACKUPDIR" Create compressed image of SD card sudo dd if=/dev/mmcblk0 bs=4M status=progress | gzip -9 > "$BACKUPDIR/$FILENAME" Rotate — keep only last N backups cd "$BACKUPDIR" ls -t ${HOSTNAME}.img.gz | tail -n +$((KEEP+1)) | xargs -r rm -- echo "Backup complete: $FILENAME" Make executable: chmod +x /home/pi/backup.sh Step 3 — Schedule with Cron sudo crontab -e Add (runs every Sunday at 2am): 0 2 0 /home/pi/backup.sh >> /home/pi/backup.log 2>&1 Restore from Backup On another computer: bash Decompress and write to new SD card gunzip -c pi-backup.img.gz | sudo dd of=/dev/sdX bs=4M status=progress Replace /dev/sdX with your SD card device. Smaller Backups with pishrink pishrink shrinks the image to actual used space (not full SD card size): wget https://raw.githubusercontent.com/Drewsif/PiShrink/master/pishrink.sh chmod +x pishrink.sh sudo ./pishrink.sh backup.img Tips
Related Guides
- Automated Plant Watering System with Raspberry Pi
- Running Home Assistant on a Raspberry Pi 4
- Kiosk Mode on Raspberry Pi: Boot Straight to a Webpage
- MQTT and Node-RED on Raspberry Pi: Visual Automation for ESP32 Sensor Networks
- Self-Hosted CI/CD Runner on a Raspberry Pi: GitHub Actions and Gitea Actions
- Getting Started with ROS2 on Raspberry Pi for Robotics
- Managing a Fleet of Raspberry Pis with Ansible: Automated Provisioning, Updates, and Config Management
- Backing Up Self-Hosted Services on Raspberry Pi with Restic and Borg