Skip to content

Instantly share code, notes, and snippets.

@bcawrse
Created April 20, 2021 19:31
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 bcawrse/3f28e9056eb06c1e79e16ef9ec6a5a48 to your computer and use it in GitHub Desktop.
Save bcawrse/3f28e9056eb06c1e79e16ef9ec6a5a48 to your computer and use it in GitHub Desktop.
script for running pg_dump against a container
#!/bin/bash
#docker_pg_dump.sh
# Thanks to StackOverflow answer by Forth
# https://stackoverflow.com/questions/24718706/backup-restore-a-dockerized-postgresql-database/29913462#29913462
HELP_MSG="
docker_pg_dump:
Call pg_dump on RUNNING docker container.
NOTE: Docker Must be installed & the postgres container must be running.
container & user are required arguments.
ARGUMENTS:
--container | -c
Running container to exec against.
--user | -u
Postgres user to use with pg_dump.
--gzip | -z
Zip results with gzip. (Default=False)
EXAMPLE:
docker_pg_dump.sh -c some-container-name -u postgres
"
while [ $# -gt 0 ]; do
case "$1" in
--container*|-c*)
if [[ "$1" != *=* ]]; then shift; fi # Value is next arg if no `=`
CONTAINER="${1#*=}"
;;
--user*|-u*)
if [[ "$1" != *=* ]]; then shift; fi
USER="${1#*=}"
;;
--gzip*|-z*)
if [[ "$1" != *=* ]]; then shift; fi
# GZIP="${1#*=}"
GZIP=true
;;
--help|-h)
echo "$HELP_MSG" # Flag argument
exit 0
;;
*)
>&2 printf "Error: Invalid argument\n"
exit 1
;;
esac
shift
done
# not fool proof, we're checking variables instead of arguments
if [[ -z ${CONTAINER} || -z ${USER} ]]
then
echo "ERROR: Missing Arguments. Please review help with --help | -h"
exit 1
fi
# here's the money
if [[ $GZIP = true ]]
then
docker exec -t $CONTAINER pg_dumpall -c -U $USER | gzip > dump_`date +%d-%m-%Y"_"%H_%M_%S`.gz
else
docker exec -t $CONTAINER pg_dumpall -c -U $USER > dump_`date +%d-%m-%Y"_"%H_%M_%S`.sql
fi
# restore - update later
# cat your_dump.sql | docker exec -i your-db-container psql -U postgres
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment