Skip to content

Instantly share code, notes, and snippets.

@Fazzani
Last active June 3, 2018 11:54
Show Gist options
  • Save Fazzani/413e4e5e5f1e6eeb91482e2f53e6c70e to your computer and use it in GitHub Desktop.
Save Fazzani/413e4e5e5f1e6eeb91482e2f53e6c70e to your computer and use it in GitHub Desktop.
backup/restore postgres
#!/bin/bash
#######################################################################################################################################
# References:
# https://devopsheaven.com/postgresql/pg_dump/databases/docker/backup/2017/09/10/backup-postgresql-database-using-docker.html
# using:
# curl -LJO https://gist.githubusercontent.com/Fazzani/413e4e5e5f1e6eeb91482e2f53e6c70e/raw/82cc5e81c07204912e6c79e647cd58850bcce27b/backup_restore_docker_postgres.sh
# chmod +x backup_restore_docker_postgres.sh
# ./backup_restore_docker_postgres.sh -b playlist # backup database playlist
# ./backup_restore_docker_postgres.sh -r dump_playlist.sql # restore database dump_playlist.sql
#######################################################################################################################################
function backup {
datetime=$(date +%d-%m-%Y"_"%H_%M_%S)
database=$1
docker exec -t "$(docker ps | grep postgres | awk '{print $1}')" /usr/bin/pg_dump -U postgres $database -c | gzip -9 > "dump_${database}_${datetime}".sql.gz
cp "dump_${database}_${datetime}.sql.gz" /mnt/freebox/TOSHIBA\ EXT/backup/postgres/synker/
rm dump_${database}_*
}
function restore {
dump_file=$1
cat $dump_file | docker exec -i "$(docker ps | grep postgres | awk '{print $1}')" psql -U postgres
}
while getopts ":b:r:" option
do
case $option in
r)
echo "Restoring from ${OPTARG} dump file"
restore $OPTARG
;;
b)
echo "Backuping ${OPTARG} database"
backup $OPTARG
;;
\?)
echo "$OPTARG : option invalide"
echo -e "backup database_name\n"
echo -e "restore dump_file_path.sql\n"
exit 1
;;
esac
done
echo "End"
exit 0
@Fazzani
Copy link
Author

Fazzani commented Jun 3, 2018

#TODO

  • check docker already exist
  • check database already exit
  • more options
    • backup : dest path
    • purge backup files
    • dump all

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