Skip to content

Instantly share code, notes, and snippets.

@marlosirapuan
Created October 12, 2019 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marlosirapuan/9dbfb99aac655f9b1e5a5f8b7a0fab0e to your computer and use it in GitHub Desktop.
Save marlosirapuan/9dbfb99aac655f9b1e5a5f8b7a0fab0e to your computer and use it in GitHub Desktop.
Tiny script to backup and restore database with Docker
#!/usr/bin/env bash
echo "BACKUPING..."
docker run -i -e PGPASSWORD=<password> --rm postgres /usr/bin/pg_dump -p <port> -h <ip> -U <user> <db> | gzip -9 > backup.sql.gz
echo "BACKUPING...[END]"
if [ -n "$1" ] ; then
where="where pg_stat_activity.datname = '<db>' AND pid <> pg_backend_pid();"
fi
cat <<-EOF | docker exec -i <container_db_local> psql -h 127.0.0.1 -U <user_db> -d postgres
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
${where}
EOF
docker exec -i <container_db_local> psql -h 127.0.0.1 -U <user_db> -d postgres -c "drop database <db_local>"
docker exec -i <container_db_local> psql -h 127.0.0.1 -U <user_db> -d postgres -c "create database <db_local>"
docker exec -i <container_db_local> pg_restore -h 127.0.0.1 -U <user_db> -w -Fc -d <db_local> backup.sql.gz
rm -rf /scripts/backup.sql.gz
echo "RESTORED."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment