How to Automate Your Server Backups with Rsync and Systemd Timers

Introduction

Automating server backups is crucial to ensure data safety and minimize manual intervention. Rsync is a powerful tool for efficiently synchronizing files, and Systemd timers provide an easy way to schedule automated tasks. This guide will walk you through setting up an automated backup system using Rsync and Systemd timers.


Step 1: Install Rsync

  1. Update your package list and install Rsync:

    sudo apt update && sudo apt install rsync -y

  2. Verify the installation:

    rsync --version


Step 2: Create a Backup Script

  1. Create a script to perform the backup:

    sudo nano /usr/local/bin/backup.sh

  2. Example script:

    #./bin/bash

    rsync -av --delete /home/user/ /backup/user/

  3. Make the script executable:

    sudo chmod +x /usr/local/bin/backup.sh


Step 3: Create a Systemd Service

  1. Define a Systemd service to execute the backup script:

    sudo nano /etc/systemd/system/backup.service

  2. Example service file: [Unit]

    Description=Automated Rsync Backup Service

    After=network.target

    [Service]

    ExecStart=/usr/local/bin/backup.sh

    Nice=19

    IOSchedulingClass=best-effort

    [Install]

    WantedBy=multi-user.target

  3. Save and close the file.


Step 4: Create a Systemd Timer

  1. Define a timer to schedule backups: sudo nano /etc/systemd/system/backup.timer

  2. Example timer file:

    [Unit]

    Description=Run Backup Service Daily

    [Timer]

    OnCalendar=daily

    Persistent=true

    [Install]

    WantedBy=timers.target

  3. Save and close the file.

  4. Reload Systemd and enable the timer:

    sudo systemctl daemon-reload

    sudo systemctl enable --now backup.timer


Step 5: Verify and Monitor Backups

  1. Check the status of the timer:

    sudo systemctl list-timers --all | grep backup

  2. Manually trigger a backup to test:

    sudo systemctl start backup.service

  3. View logs to ensure backups are running:

    sudo journalctl -u backup.service --no-pager


Conclusion

By using Rsync and Systemd timers, you can automate your server backups efficiently and reliably. Adjust the script and scheduling as needed to fit your backup requirements.