Skip to main content

Backup/restore docker database to local file system

Updated by Tim Rabbetts on
technology, servers, server

I've written a script to backup and restore my databases from a docker container to local file system.  Its a bit hacky but I keep a months worth of backups by checking the date, if its the first I get rid of ever backup from the month 2 before.

#!/bin/bash
echo "DB Backup script started ..."

source .env

DATESTAMP=$(date +"%m.%d.%Y")
DAY=$(date +"%-d")
MONTH=$(date +"%-m")
YEAR=$(date +"%-Y")
PREV_MONTH=$(($MONTH-2))
PREV_MONTH=$(printf "%02d" $PREV_MONTH)
BACKUP_FOLDER="/backups/db/${APP_PREFIX}"
BACKUP_PATH="${BACKUP_FOLDER}/${DATESTAMP}.sql.gz"

mkdir -p ${BACKUP_FOLDER}

if [[ "$DAY" == "01" ]]
then
  # clear out the month before last month so we keep a month rolling window.
  echo "Removing old backups ${BACKUP_FOLDER}/${PREV_MONTH}.*.${YEAR}_*.gz"
  rm -rf ${BACKUP_FOLDER}/${PREV_MONTH}.*.${YEAR}_*.gz
fi

echo "Starting back up database ..."
echo "DB=${DB_DATABASE}"
echo "BACKUP_FOLDER=${BACKUP_FOLDER}"
echo "BACKUP_PATH=${BACKUP_PATH}"

docker-compose exec ${DB_HOST} bash -c "mysqldump -u root -p${DB_PASSWORD} ${DB_DATABASE} | /bin/gzip > \"db/${DATESTAMP}.sql.gz\""

mv db/${DATESTAMP}.sql.gz ${BACKUP_PATH}

echo "Database Backups Complete."

 

Add new comment