How to Backup MongoDB in Docker Environment

Randula Koralage
2 min readOct 7, 2022

--

Photo by benjamin lehman on Unsplash

Docker containers act as separate isolated components on top of the host environment. MongoDB also can be run as a container. As you know, anything that creates or stores inside the container is removed when the container is deleted. So to persist the data on the local machine it needs to mount a volume when the mongo container creates.

docker run — name mongodb -d -v LOCAL_DIR:/data/db mongo

mongodump and mongorestore commands are normally used in MongoDB to backup and restore processes. When it comes to dockerization, you’ll need to execute the commands on bash for the MongoDB container.

How to open bash for MongoDB?

As same as any container, the docker exec command can be used to open the shell for MongoDB container.

docker exec -it MONGO_CONTANER_NAME sh

Taking DB Backups

From the bash shell, you can execute the usual mongodump commands.

ex:

mongodump -h localhost:27017 -d DB_NAME -o .

Your dump is created inside the container unless otherwise, you have mounted the backup volume with your local machine. Also, you can copy the backup to your local machine. Please refer following steps.

  • Creating the backup

docker exec -it MONGO_CONTAINER sh
mkdir
backup
cd
backup
mongodump -h localhost:27017 -d DB_NAME -o .

  • Copy the backup to the host machine

cd HOST_FOLDER
docker cp mongodb-dev2:/backup .

The MongoDB setup can come with different configurations. Please refer following blogs of mine to get a full idea of Backing Up MongoDB in Docker.

--

--