Skip to content

Instantly share code, notes, and snippets.

@cr-pl
Last active January 3, 2025 15:23
Show Gist options
  • Save cr-pl/c285c9907ea1ea210e96a551ffc1a6bb to your computer and use it in GitHub Desktop.
Save cr-pl/c285c9907ea1ea210e96a551ffc1a6bb to your computer and use it in GitHub Desktop.
Backup database hosted in a docker container. The script will be executed on host machine.
#!/bin/sh
###########################################################
#server variables
DBUSER="db_user"
DBPASS="my_secret_password"
DBNAME="my_db"
DBCONTAINER="my_docker_container"
CONTAINERPATH="/var/docker"
###########################################################
#script variables
BKDATETIME="$(date '+%Y-%m-%d-%I-%M-%S')"
BACKUPDIR="$CONTAINERPATH/$DBCONTAINER/backup"
DUMPFILENAME="$DBNAME-$BKDATETIME.sql"
ZIPFILENAME="$DUMPFILENAME.zip"
###########################################################
echo $BKDATETIME
#cd dirname "$(realpath $0)"
cd $BACKUPDIR
echo "Saving dumpfile $DUMPFILENAME."
#not recommended way:
#docker exec $DBCONTAINER mysqldump --add-drop-table -u $DBUSER -p$DBPASS $DBNAME > $BACKUPDIR/$DUMPFILENAME
#it is recommended to store mysql credentials in an external file
docker exec $DBCONTAINER mysqldump --defaults-extra-file=/etc/mysql/conf.d/mysqldump.cnf --add-drop-table $DBNAME > $BACKUPDIR/$DUMPFILENAME
echo "archiving dump-file"
zip -q $BACKUPDIR/$ZIPFILENAME $DUMPFILENAME
rm -f $BACKUPDIR/$DUMPFILENAME
echo "------------------------------------------"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment