Export/Dump Docker MongoDB database

There are tons of articles explaining how to export/dump a Mongo database from Docker, all of which we seemed to struggle with. The following script allows you to dump your Mongo database to a zip file:


# Usage: ./mongo-backup.sh [$1 database_name] [$2 username] [$3 password] [$4 output_filename]

echo 'Preparing to dump data'
rm -rf ~/Desktop/mongodump && mkdir ~/Desktop/mongodump
echo 'Dumping data'
docker run --rm --link CONTAINER_NAME:mongo -v ~/Desktop/mongodump:/tmp mongo bash -c 'mongodump -v -u'$2' -p'$3' --host $MONGO_PORT_27017_TCP_ADDR:$MONGO_PORT_27017_TCP_PORT --db '$1' --out=/tmp'
echo 'Dumping complete, creating zip'
zip -r ~/Desktop/$4 ~/Desktop/mongodump/
echo 'Zip complete, cleaning up'
rm -rf ~/Desktop/mongodump
echo 'Completed'

The first thing to do prior to running the above script is to start the Docker container that you wish to backup. Next you can run a command similar to the following:

sh ~/Desktop/backup.sh DB_NAME DB_USERNAME DB_PASSWORD backup.zip

This will dump your database and zip the dump in a file called backup.zip