DEV Community

loading...

How to backup a Docker MySQL database

grant_bartlett profile image Grant ・1 min read

Simple bash script and cron example to backup a MySQL database from within a Docker container.

Replace <CONTAINER_NAME> with your MySQL container name or id.

Create a backup.sh and run bash backup.sh

#!/bin/bash
BACKUP_DIR="/home/backups"
BACKUP_FILE_NAME="$(date +"%d-%m-%y-%H%M%S.sql.gz")"

docker exec <CONTAINER_NAME> bash -c 'exec mysqldump --databases "$MYSQL_DATABASE" -h<DOCKER_MYSQL_SERVICE_NAME> -u"$MYSQL_USER" -p"$MYSQL_PASSWORD"' > gzip > "$BACKUP_DIR"/"$BACKUP_FILE_NAME";
Enter fullscreen mode Exit fullscreen mode

You could then edit your cron to run it daily, something like:
crontab -e

0 0 * * * cd /path/to/script && bash ./backup.sh >> /path/to/log/backup.log
Enter fullscreen mode Exit fullscreen mode

More examples can be found on the MySQL docker page.

Discussion (0)

pic
Editor guide