Last active
September 16, 2020 08:03
-
-
Save dommmel/f79d4d648517ef015682 to your computer and use it in GitHub Desktop.
dokku postgres backup cronjob (using https://github.com/Kloadut/dokku-pg-plugin)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/bash | |
# directory to save backups in, must be rwx by postgres user | |
BASE_DIR="/var/backups/postgres" | |
YMD=$(date "+%Y-%m-%d") | |
DIR="$BASE_DIR/$YMD" | |
mkdir -p $DIR | |
cd $DIR | |
# make database backup | |
dokku postgresql:dump $1 | gzip -9 > "$DIR/db.out.gz" | |
# delete backup files older than 7 days | |
OLD=$(find $BASE_DIR -type d -mtime +7) | |
if [ -n "$OLD" ] ; then | |
echo deleting old backup files: $OLD | |
echo $OLD | xargs rm -rfv | |
fi |
- stick this script somewhere on your machine.
- crontab -e
- add the following line:
0 0 * * * PATH_TO_THE_SCRIPT NAME_OF_YOUR_DB - close the editor
Now your database will back up every night at midnight.
I had to remove the | gzip -9
part or the file would be empty.
Also added hourly backups and longer retention:
#! /bin/bash
# directory to save backups in, must be rwx by postgres user
BASE_DIR="/var/backups/postgres"
YMD=$(date "+%Y-%m-%d-%H-%M-%S")
DIR="$BASE_DIR/$YMD"
mkdir -p $DIR
cd $DIR
# make database backup
dokku postgresql:dump $1 > "$DIR/db.dump"
# delete backup files older than 30 days
OLD=$(find $BASE_DIR -type d -mtime +30)
if [ -n "$OLD" ] ; then
echo deleting old backup files: $OLD
echo $OLD | xargs rm -rfv
fi
For hourly script launching, setup crontab this way:
0 * * * * PATH_TO_THE_SCRIPT NAME_OF_YOUR_DB
I've a problem when running it when deploying is it not the same bahaviour ?
remote: mkdir: cannot create directory ‘/var/backups/postgres’: Permission denied
remote: dokku-pg-backup.sh: 6: cd: can't cd to /var/backups/postgres/2016-03-14
remote: dokku-pg-backup.sh: 9: dokku-pg-backup.sh: dokku: not found
remote: dokku-pg-backup.sh: 9: dokku-pg-backup.sh: cannot create /var/backups/postgres/2016-03-14/db.out.gz: Directory nonexistent
On Ubuntu 16.04.03 with the last version of dokku and postresql plugin.
I change this line on the script to make it works :
dokku postgresql:dump $1 > "$DIR/db.dump"
TO
dokku postgres:export $1 > "$DIR/db.dump"
Also :
Dont forget to make it executable with sudo chmod +x yourscript.sh
.
If you want to test it, do it with sudo ./yourscript.sh DBName
If you want to create a cron, use sudo crontab -e
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sorry, i'm a bit of a newb with all the bash stuff, how exactly do I got about setting this up?