Last active
November 1, 2021 11:48
-
-
Save R0Wi/29b7ebe3b7dfec1689cb43dd1534dfcc to your computer and use it in GitHub Desktop.
Bash script to backup all running MySQL docker instances via mysqldump
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Script to backup all running mysql docker instances | |
# | |
# Usage: | |
# Set the BACKUP_TARGET_DIR variable and call the script. Note that | |
# the mysql containers must either have set the MYSQL_ROOT_PASSWORD environment variable | |
# or the MYSQL_DATABASE MYSQL_USER MYSQL_PASSWORD environment variables. | |
# | |
# AUTHOR Robin Windey | |
# EMAIL [email protected] | |
BACKUP_TARGET_DIR="<HOST_PATH>" | |
MYSQL_VOLUME="/var/lib/mysql" | |
readarray -t running_containers_arr < <(docker ps --format='{{.ID}}') | |
for container in ${running_containers_arr[@]}; do | |
docker inspect $container --format="{{.Config.Volumes}}" | grep "$MYSQL_VOLUME" -q | |
# It's most likely a MYSQL container | |
if [ $? -eq 0 ]; then | |
container_name=$(docker inspect $container --format="{{.Name}}" | tr -d "/") | |
readarray -t environment_arr < <(docker inspect $container --format="{{range .Config.Env}}{{println .}}{{end}}") | |
root_pw="" | |
db="" | |
user="" | |
pw="" | |
for env_var in ${environment_arr[@]}; do | |
(echo "$env_var" | grep -q "MYSQL_ROOT_PASSWORD") && root_pw=$(echo "$env_var" | sed -e 's/MYSQL_ROOT_PASSWORD=//g') && break | |
(echo "$env_var" | grep -q "MYSQL_DATABASE") && db=$(echo "$env_var" | sed -e 's/MYSQL_DATABASE=//g') && continue | |
(echo "$env_var" | grep -q "MYSQL_USER") && user=$(echo "$env_var" | sed -e 's/MYSQL_USER=//g') && continue | |
(echo "$env_var" | grep -q "MYSQL_PASSWORD") && pw=$(echo "$env_var" | sed -e 's/MYSQL_PASSWORD=//g') && continue | |
done | |
echo "Run backup for ${container_name}" | |
tmp_target="${MYSQL_VOLUME}/${container_name}.sql.gz" | |
if [ ! -z "$root_pw" ]; then | |
# if we have a root pw we use this to backup all databases in this instance | |
docker exec $container bash -c "export MYSQL_PWD=$root_pw; /usr/bin/mysqldump -u root --all-databases | gzip -9 -c > $tmp_target" | |
else | |
# Otherwise we just backup one db | |
docker exec $container bash -c "export MYSQL_PWD=$pw; /usr/bin/mysqldump -u $user --no-tablespaces $db | gzip -9 -c > $tmp_target" | |
fi | |
# Copy to host system | |
docker cp $container:$tmp_target $BACKUP_TARGET_DIR | |
docker exec $container rm -f $tmp_target | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment