How to Clone a MongoDB Database Between Docker Containers
How to Clone a MongoDB Database Between Docker Containers
If you're running MongoDB in Docker and want to clone a database from one container to another, you're in the right place. This guide walks you through exporting a MongoDB database from one Docker container and restoring it into another — all using Docker commands and MongoDB’s native tools.
Prerequisites
- Docker installed on your system
- Two MongoDB containers:
- Source container:
mongo_source
- Target container:
mongo_target
- Source container:
- Database to clone:
mydb
Step 1: Dump the Database from the Source Container
Use the mongodump
command inside the mongo_source
container to export the contents of mydb
:
docker exec mongo_source mongodump --db=mydb --out=/dump
This command creates a dump in the /dump
directory inside the container.
Next, copy that dump to your host machine:
docker cp mongo_source:/dump ./dump
You now have a local copy of your database dump in the ./dump
folder on your host.
Step 2: Transfer the Dump to the Target Container
Now that the dump is on your host, copy it into the mongo_target
container:
docker cp ./dump mongo_target:/dump
Step 3: Restore the Dump into the Target MongoDB
Run the mongorestore
command inside the mongo_target
container:
docker exec mongo_target mongorestore --db=mydb /dump/mydb
Want to restore it to a different database name? You can! Just use the --nsFrom
and --nsTo
flags:
docker exec mongo_target mongorestore --nsFrom='mydb.*' --nsTo='newdb.*' /dump/mydb
Step 4: Clean Up (Optional but Recommended)
Once the database is cloned, you can safely delete the dump files from both the host and the containers:
rm -rf ./dump
docker exec mongo_source rm -rf /dump
docker exec mongo_target rm -rf /dump
Pro Tips
- Authentication: If your MongoDB uses authentication, add
-u
,-p
, and--authenticationDatabase
to yourmongodump
andmongorestore
commands. - Custom Ports: If MongoDB is running on a custom port, you can specify it with
--port
.
Conclusion
You’ve successfully cloned a MongoDB database between two Docker containers. Whether you’re migrating environments or setting up test data, this technique is quick, reliable, and easy to repeat.
Comments
Post a Comment