Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save farhad0085/4aa53d899893686bbc7f2385c0436419 to your computer and use it in GitHub Desktop.
Save farhad0085/4aa53d899893686bbc7f2385c0436419 to your computer and use it in GitHub Desktop.
Automate postgresql database backup to google drive

Automate postgresql database backup to google drive

  1. Install and setup google-drive-upload

    To install google-drive-upload in your system, you can run the below command:

    curl --compressed -Ls https://github.com/labbots/google-drive-upload/raw/master/install.sh | sh -s
    

For more information on installation and setup, please follow this: https://labbots.github.io/google-drive-upload/setup/install/

  1. Create a file called backup-db-to-drive.sh and paste following code there.
    #!/bin/bash
    export PATH=$PATH:/home/your_username/.google-drive-upload/bin/ # path to google-drive-upload executable, usually in your user
    export PGPASSWORD="db_password"
    
    # make the database dump first
    pg_dump db_name -U db_username -h localhost > /home/your_username/db-backup/db_dump_`date +%d-%m-%Y"_"%H_%M_%S`.sql
    
    # now upload to drive
    gupload db-backup -d
    
    # now delete all files from db-backup folder, because we have limited storage
    rm -f /home/your_username/db-backup/*

Please replace your_username, db_name, db_username and db_password with suitable details

  1. Make the above file executable

    sudo chmod +x backup-db-to-drive.sh
  2. Run the above file manually, paste following code in the terminal and smash enter button in your keyboard

    ./backup-db-to-drive.sh
    

    If you see the database is backup successfully and uploaded to google drive then move to next step, otherwise see the installation link again and again until you resolve the issue. In addition, check your_username, db_name, db_username and db_password carefully.

  3. The above file will create a folder in your google drive called 'db-backup', see if it created the folder and uploaded the db backup or not.

  4. If everything is good, now it's time to set the cron. In the cron we'll basically run this file every friday.

  5. Open crontab by running crontab -e and paste following code.

    # backup database every friday
    0 0 * * 5 bash ~/backup_db_to_drive.sh >> /home/your_username/db-backup/cron.log 2>&1
    
  6. Done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment