Skip to content

Instantly share code, notes, and snippets.

@guilhermegazzinelli
Last active January 14, 2024 21:26
Show Gist options
  • Save guilhermegazzinelli/9f1c1cb3b30744373b87a10366eabb2b to your computer and use it in GitHub Desktop.
Save guilhermegazzinelli/9f1c1cb3b30744373b87a10366eabb2b to your computer and use it in GitHub Desktop.
Backup postgres inside docker container
#!/bin/bash
#### Definitions
db_username=user
container_filter=cimentao_db
backup_dir=/home/ubuntu/backup
### Variables
date=`date +%Y-%m-%d"_"%H_%M_%S`
filename=dump_$date.gz
### Process
echo -n -e "\e[39mStarting Backup >> "
cd $backup_dir
echo -e '=> \e[33mDeleting backups but mantainning last 7 days'
ls -tr dump* | head -n -14 | xargs --no-run-if-empty rm
CONTAINER_NAME=`docker ps --filter "name=$container_filter" --format "{{.Names}}"`
docker exec -t $CONTAINER_NAME pg_dumpall -c -U $user | gzip -9 > $filename
if test -f "$filename"; then
echo -n -e "\e[32m$filename: \e[39m `ls -lh $filename | awk -v col=5 '{print $col}'` >> Gzip file is: "
if gzip -t $filename; then
echo -e '\e[32mOK'
exit 0
else
echo -e '\e[31mFAIL!!!'
gzip -t -v $filename
exit 1
fi
else
echo -e "file $filename \e[31mNOT FOUND"
exit 0
fi
echo -e '=> \e[33mDeleting backups but mantainning last 7 days'
ls -tr dump* | head -n -14 | xargs --no-run-if-empty rm
echo -e '=>\e[32mBackup Done'
## CRONTAB -E
0 15,22 * * * cd /home/ubuntu/backup/ && sh backup.sh >> backup.log
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment