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)
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
Yes nice spot! I will update my post.
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
Thanks Raj, i will update the post!
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 emptydb.dump
file. Here's what worked for me: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