Mongodump and mongorestore with Docker
Story
If you want to backup, export and migrate the MongoDB schema, you can use MongoDB Tools or command-line
And today i will presentation about command-line utilities mongorestore and mongodump with Docker.
A. Export data with mongodump
- Create mongodb container with Docker
- (create without authentication)
docker run -d --name mongodb -p 27017:27017 mongo:latest
- (create secure with username/password)
docker run -d --name mongodb -p 27017:27017 -u username -p password mongo:latest
- (create with existing data)
docker run -d --name mongodb -p 27017:27017 -v $PATH_OF_MONGODB_VOLUME/data:/data/db mongo:latest
You can find PATH_OF_MONGODB_VOLUME with command "docker inspect" and you will see the "Mounts" section in the output.
- Exec to the mongodb container (bash)
docker exec -it mongodb bash
- To export the data, use command "mongodump" and the output path name "dump_backup"
mongodump -o dump_backup
- (secure with username/password)
mongodump -u username -p password -o dump_backup
So, the dump_backup file have been created. But the output file (dump_backup) is created inside the container's filesystem. So you need need to copy it from the container to your host (local).
- Copy dump_backup file from container to local.
docker cp $CONTAINER_NAME:/$BACKUP_FILE_NAME/$DATABASE_NAME PATH_TO_LOCAL
docker cp mongodb:/dump_backup/blogs /Desktop/backup/dump_backup_local
Now. In the local, access to path ../Desktop/backup/dump_backup, you will see the binary files of a database
B. Import data with mongorestore
- Copy file from local to the docker container
docker cp /Desktop/backup/dump_backup_local mongodb:/dump_backup
- Exec to container and import the dump_backup file to the mongodb
mongorestore -u $USERNAME -p $PASSWORD --authenticationDatabase=admin -d $DATABASE_NAME $BACKUP_FILE_NAME
mongorestore -u username -p password --authenticationDatabase=admin -d blogs /dump_backup (if with secure username/password)
mongorestore -d blogs /dump_backup (if without secure username/password)
Finally
If the database just deploy production. You only ssh to the host and do the same. I hope you find the information here useful