Skip to content

Instantly share code, notes, and snippets.

@oniksfly
Created March 11, 2018 14:08
Show Gist options
  • Save oniksfly/09365a738a3b620d81ffbb11de5b6e4d to your computer and use it in GitHub Desktop.
Save oniksfly/09365a738a3b620d81ffbb11de5b6e4d to your computer and use it in GitHub Desktop.
Backup PostreSQL database from docker container
# /bin/bash
echo "Backup script is running"
PG_DOCKER_CONTAINER="postgres"
PG_USERNAME="postgres"
DATABASE="default_database"
HOMEPATH=$(cd ~ && pwd)
COLOR_NORMAL="\033[0m"
COLOR_GREEN="\033[0;32m"
echo "Database ${COLOR_GREEN}${DATABASE}${COLOR_NORMAL} will be backed up. Press ENTER or type new database name:"
read INPUT_DATABASE < "${1:-/dev/stdin}"
if (($(printf "%s" "$INPUT_DATABASE" | wc -c) > 0))
then
DATABASE=$INPUT_DATABASE
echo "Changing database to ${COLOR_GREEN}${DATABASE}${COLOR_NORMAL}"
fi
if [ "$(docker exec $PG_DOCKER_CONTAINER bash -c "psql -U $PG_USERNAME -tAc \"SELECT 1 FROM pg_database WHERE datname='$DATABASE'\"")" = '1' ]
then
NAME="${DATABASE}_$(date +"%Y-%m-%d_%H-%M")"
echo "Backup in progress"
else
echo "No database $DATABASE found"
fi
docker exec $PG_DOCKER_CONTAINER bash -c "pg_dump -U $PG_USERNAME $DATABASE > /tmp/$NAME.sql" && \
docker cp $PG_DOCKER_CONTAINER:/tmp/$NAME.sql $HOMEPATH/ && \
tar czf $NAME.sql.tar.gz $NAME.sql && \
rm $NAME.sql && \
docker exec $PG_DOCKER_CONTAINER bash -c "rm /tmp/$NAME.sql"
echo "Backup placed at $HOMEPATH/$NAME.sql.tar.gz"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment