Skip to content

Instantly share code, notes, and snippets.

@dommmel
Last active September 16, 2020 08:03
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save dommmel/f79d4d648517ef015682 to your computer and use it in GitHub Desktop.
Save dommmel/f79d4d648517ef015682 to your computer and use it in GitHub Desktop.
dokku postgres backup cronjob (using https://github.com/Kloadut/dokku-pg-plugin)
#! /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
@hakunin
Copy link

hakunin commented Apr 19, 2015

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

@pythdasch
Copy link

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

@Holist
Copy link

Holist commented Dec 15, 2017

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