Skip to content

Instantly share code, notes, and snippets.

@mjdubell mjdubell/backup.sh
Created Sep 9, 2017

Embed
What would you like to do?
Database backup and verification using Docker.
#!/bin/bash
# Get current date with format: Y-m-d_HMS
date=$(date +%Y-%m-%d_%H%M%S);
# Backup location
BACKUP_LOC='/srv/postgres/';
DB_SUCCESS='success/';
DB_UNTESTED='untested/';
DB_FAILED='failed/';
# Log location
LOG_FILE='/srv/postgres/log/';
# Email address
EMAIL='';
# Postgres environment variables
export PGUSER='';
export PGHOST='';
export PGDATABASE='';
export PGPASSWORD='';
DOCKER_PGPORT='';
DOCKER_PGPASSWORD='';
BACKUP_FILENAME=${BACKUP_LOC}${DB_UNTESTED}${PGDATABASE}_${date}.sql;
echo "[*] Creating a postgres docker container..."
# Attempt to resore the database with a docker instance running postgres
docker run -d --name ${PGDATABASE}_${date} -p $DOCKER_PGPORT:5432 -e POSTGRES_PASSWORD=$DOCKER_PGPASSWORD -e POSTGRES_USER=$PGUSER -e POSTGRES_DB=$PGDATABASE postgres
# We need to wait for docker to fully initialize before we can start restoring data
sleep 10
# Change to postgres user
#su postgres
cd /var/lib/pgsql
echo "[*] Dumping the database..."
# Dump the database
if ! su -c "pg_dump --verbose -wF c ${PGDATABASE} > ${BACKUP_FILENAME} 2> ${LOG_FILE}${PGDATABASE}_${date}.dump.txt" postgres
then
echo "[-] pg_dump error..." >> cat ${LOG_FILE}${PGDATABASE}_${date}.dump.txt
cat ${LOG_FILE}${PGDATABASE}_${date}.dump.txt | mail $EMAIL -s "Postgresql database dump failure!"
mv ${BACKUP_FILENAME} ${BACKUP_LOC}${DB_FAILED}${PGDATABASE}_${date}.sql
docker kill ${PGDATABASE}_${date}
docker rm ${PGDATABASE}_${date}
exit 1;
fi
export PGPORT=$DOCKER_PGPORT;
export PGPASSWORD=$DOCKER_PGPASSWORD;
echo "[*] Testing the database backup with docker..."
if ! su -c "pg_restore --no-owner --exit-on-error -d ${PGDATABASE} -F c ${BACKUP_FILENAME} 2> ${LOG_FILE}${PGDATABASE}_${date}.restore.txt" postgres
then
echo "[-] pg_restore error..." >> ${LOG_FILE}${PGDATABASE}_${date}.restore.txt
cat ${LOG_FILE}${PGDATABASE}_${date}.restore.txt | mail -s "Postgresql database dump failure!" $EMAIL
mv ${BACKUP_FILENAME} ${BACKUP_LOC}${DB_FAILED}${PGDATABASE}_${date}.sql
docker kill ${PGDATABASE}_${date}
docker rm ${PGDATABASE}_${date}
exit;
else
# Great success, no errors!
gzip $BACKUP_FILENAME
mv ${BACKUP_FILENAME}.gz ${BACKUP_LOC}${DB_SUCCESS}${PGDATABASE}_${date}.sql.gz
fi
# Remove containers
echo "[*] Cleaning up..."
docker kill ${PGDATABASE}_${date}
docker rm ${PGDATABASE}_${date}
echo "[!] Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.