DEV Community

Cover image for 🐳 mongodump and mongorestore with Docker
Kubdev
Kubdev

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.

Discussion (4)

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
Kubdev Author

Thanks Raj, i will update the post!

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
Kubdev Author

Yes nice spot! I will update my post.