Skip to content

Instantly share code, notes, and snippets.

@sebastian13
Last active July 28, 2023 20:41
Show Gist options
  • Save sebastian13/c313c055a59342acb9f0a7a3d5d03c09 to your computer and use it in GitHub Desktop.
Save sebastian13/c313c055a59342acb9f0a7a3d5d03c09 to your computer and use it in GitHub Desktop.
curl -JO https://gist.githubusercontent.com/sebastian13/c313c055a59342acb9f0a7a3d5d03c09/raw/docker-postgres-dump.sh
curl -JO https://gist.githubusercontent.com/sebastian13/c313c055a59342acb9f0a7a3d5d03c09/raw/docker-postgres-restore.sh
chmod +x docker-postgres-(dump|restore).sh
#!/bin/bash
set -e
# Change to the script's directory & create directory
cd $(dirname "$(readlink -f "$0")")
mkdir -p ./pgdumps
# Start postgres service
docker --log-level=error compose up -d postgres
sleep 5
# Load database name + username
source .env
# Delete old Backups
find ./pgdumps/ -name "*.bak.gz" -atime +7 -exec rm {} \;
# Set the filename
dump="`date +\%Y\%m\%d-\%H\%M`-$POSTGRES_DB.bak.gz"
docker compose exec -T postgres /usr/bin/pg_dump $POSTGRES_DB -U $POSTGRES_USER \
| gzip --rsyncable > ./pgdumps/$dump
ln -fs $dump ./pgdumps/latest.bak.gz
#!/bin/bash
# Start postgres service
docker --log-level=error compose up -d postgres
sleep 5
# Load username
source .env
# Find latest dump
latest=$(ls -1t ./pgdumps/*.bak.gz | head -1)
# Restore
gunzip -c $latest | docker compose exec -T postgres /usr/bin/psql -U $POSTGRES_USER $POSTGRES_DB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment