DEV Community

Cover image for 🐳 mongodump and mongorestore with Docker
Maxime Kubik
Maxime Kubik

Posted on • Updated on

🐳 mongodump and mongorestore with Docker

Hi! TIL how to restore and dump a MongoDB container. The trick is to disable pseudo-tty allocation. Otherwise extra characters are added to the backup file. They prevent mongorestore from working properly.

With Docker

With docker, pseudo-tty allocation is deactivated by default, but the -i (interactive) option is required with the restore command.

mongodump

  • No Auth : docker exec <mongodb container> sh -c 'mongodump --archive' > db.dump

  • Authenticated : docker exec <mongodb container> sh -c 'mongodump --authenticationDatabase admin -u <user> -p <password> --db <database> --archive' > db.dump

mongorestore

  • No Auth : docker exec -i <mongodb container> sh -c 'mongorestore --archive' < db.dump

  • Authenticated : docker exec -i <mongodb container> sh -c 'mongorestore --authenticationDatabase admin -u <user> -p <password> --db <database> --archive' < db.dump

With Docker Compose

With docker-compose, pseudo-tty allocation needs to be deactivated explicitly each time with -T :

mongodump

docker-compose exec -T <mongodb service> sh -c 'mongodump --archive' > db.dump

mongorestore

docker-compose exec -T <mongodb service> sh -c 'mongorestore --archive' < db.dump

That's all ! ✨🎉
Now, feel free to write a script and add it to your pipeline.

Top comments (6)

Collapse
 
punkte profile image
Punkte

Hi, some people may have an error running with docker compose in a dev environement.

I got the following error:
Failed: can't create session: could not connect to server: connection() : auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.

In order to resolve this I had to specify the authenticationDatabase with the flag --authenticationDatabase admin

Collapse
 
mkubdev profile image
Maxime Kubik

Yes nice spot! I will update my post.

Collapse
 
rajmaharjan profile image
Raj Maharjan

Hi, thanks for writing, useful for quick note.
Here, mongorestore authenticated only worked with -i option:
docker exec -i <mongodb container> sh -c 'mongorestore -d <database> -u <user> -p <password> --archive' < db.dump

Collapse
 
mkubdev profile image
Maxime Kubik

Thanks Raj, i will update the post!

Collapse
 
dodov profile image
Hristiyan Dodov

It didn't work for me with sh -c. The resulting MongoDB dump simply wasn't getting printed to stdout and I was getting an empty db.dump file. Here's what worked for me:

docker exec mongo mongodump --archive "mongodb+srv://user:pass@my-db.mongodb.net/?retryWrites=true&w=majority" > db.dump
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vivekrahul profile image
Vivek Rahul

Hi, after mongorestore command it shows,
28 document(s) restored successfully. 0 document(s) failed to restore.

But theres no data when i hit the api in postman/browser