[HOW TO] Docker backup mongo

This question is asked frequently.

How do I backup and restore a mongo DB in a docker container.

We first need to find the container label. You may need sudo for the following commands.

docker ps -a


So we need to do this:

docker exec docker_mongo_1 sh -c 'mongodump --archive' > db.dump

And in the current directory you should find db.dump

Restore should be the reverse process:

docker exec -i docker_mongo_1 sh -c 'mongorestore --archive' < db.dump

This is quite a good guide though I couldn’t get the compose variant to work (and my test container is built with compose)


What did you experience with docker-compose? A parse error? Something about corrupted backup?

Surprisingly neither. When I ran the commands as per the page it outputs nothing.

I need to play a bit more.

Try manually setting COMPOSE_INTERACTIVE_NO_CLI to false and run the commands again. If call_docker() is not being used, stdout and stderr streams don’t get decoupled.

In dockerpty.pty.ExecOperation().start():

pumps.append(io.Pump(stream, io.Stream(self.stdout), propagate_close=False))
        # FIXME: since exec_start returns a single socket, how do we
        #        distinguish between stdout and stderr?
        # pumps.append(io.Pump(stream, io.Stream(self.stderr), propagate_close=False))

In my case this was the issue, didn’t get any output after the mongodump command and the log information corrupted the backup file.

Another option could be using mongodump --archive --quiet to remove the log altogether. Or forward stderr from inside the sh -c block.


COMPOSE_INTERACTIVE_NO_CLI=false docker-compose exec -T mongo mongodump --archive >db.dump

PS. sh -c isn’t necessary, I don’t know why the super author used that.

Ref: Compose CLI environment variables | Docker Documentation