Last active
August 31, 2022 13:22
-
-
Save m-ocean-it/eef5ef335a02df836b7738497a4690ba to your computer and use it in GitHub Desktop.
Backup PostgreSQL DB running in Docker container
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/zsh | |
# Constants { | |
postgres_container_name="" | |
main_user="" | |
# } | |
# Make a copy of the DB files within the container | |
postgres_home_dir=$(docker exec --user postgres $postgres_container_name bash -c "echo \$HOME") | |
postgres_backup_container_dir="$postgres_home_dir/backup" | |
cmd="rm -rf $postgres_backup_container_dir ; pg_basebackup -U \$POSTGRES_USER -D $postgres_backup_container_dir --format=plain --write-recovery-conf --checkpoint=fast --progress && echo SUCCESS" | |
docker exec --user postgres -t $postgres_container_name bash -c $cmd | |
# Copy the DB files to the host | |
main_user_home_dir=$(cat /etc/passwd | grep $main_user | cut -d : -f 6) | |
host_backup_dir="$main_user_home_dir/backup" | |
docker cp $postgres_container_name:$postgres_home_dir/backup $host_backup_dir | |
# (If you wonder why not copy the DB files right away then know that doing | |
# so poses a risk of data corruption. pg_basebackup is a utility for safely | |
# copying DB files. Then, the copied files are safe to read since they are | |
# backup, i.e. not being read by the DB.) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment