Database Backup Import

@imarikchakma · Dec 25, 2023

When you are working with docker, you might need to import data from a backup file. Here is a single command to import data in MySQL and MongoDB from backup.

MySQL

docker cp /path/to/your/backup.sql.gz MYSQL_CONTAINER:/tmp/backup.sql.gz && \
docker exec -it MYSQL_CONTAINER bash -c "\
zcat /tmp/backup.sql.gz > /tmp/backup.sql && \
mysql -u root -p DATABASE_NAME < /tmp/backup.sql && \
rm /tmp/backup.sql.gz && \
rm /tmp/backup.sql"

MongoDB

docker cp /path/to/your/backup.tar.gz MONGO_CONTAINER:/tmp/backup.tar.gz && \
docker exec -it MONGO_CONTAINER bash -c "\
mongorestore --gzip --archive=/tmp/backup.tar.gz --nsInclude='DATABASE_NAME.*' && \
rm /tmp/backup.tar.gz"

Note: If you want to import to a specific collection, replace DATABASE_NAME.* with DATABASE_NAME.COLLECTION_NAME.