A Simple Way to Backup MySQL in a Docker Container
When running MySQL inside a Docker container, backing up your databases might seem complicated since the database engine isn’t installed directly on your host machine.
However, you can use the docker exec command to execute mysqldump directly inside the running container and output the result to a file on your host machine.
Here is the simple, one-line command to back up a MySQL database running in Docker:
docker exec <container_name> /usr/bin/mysqldump -u root --password=root <database_name> > backup.sql
Explanation of the Command
docker exec <container_name>: This tells Docker to execute a command inside the specified running container./usr/bin/mysqldump: The path to themysqldumputility inside the container.-u root --password=root: The username and password needed to connect to the MySQL instance.<database_name>: The specific database you want to back up.> backup.sql: This redirects the output generated inside the container to a file namedbackup.sqlon your host machine.
Creating an Automated Backup Script
If you want to run this automatically on a schedule, you can create a simple bash script that includes a timestamp in the filename:
#!/bin/bash
TIMESTAMP=$(date +"%F")
BACKUP_DIR="/path/to/backups"
MYSQL_USER="root"
MYSQL_PASSWORD="my_secure_password"
DATABASE_NAME="my_database"
CONTAINER_NAME="my_mysql_container"
docker exec $CONTAINER_NAME /usr/bin/mysqldump -u $MYSQL_USER --password=$MYSQL_PASSWORD $DATABASE_NAME > $BACKUP_DIR/$DATABASE_NAME-$TIMESTAMP.sql
You can then add this script to your host machine’s crontab to run daily or weekly.