Dockerize Mongo to get consistent data across your development environments
We have all lamented, with great chagrin, the proverbial “works on my machine” problem because data is different across different development environments.
Wouldn’t it be ideal if we could deploy our MongoDB database state from a single repository on all development environments?
In this tutorial, we will be dockerizing a Mongo database with some seed data so we can do just that!
Prerequisites
- Install Docker Desktop
- Install MongoDB Compass (for testing)
Step-by-Step How-To
Step 1: Download and unzip the file TonicMongoDockerTutorial_start.zip
- The structure should look as follows:
- The purposes of each of these files are as follows:
docker-compose.ymlwill orchestrate our two containers; one holding the actual database, the other acting as a client ‘seeder’ to seed our data.Dockerfilewill be the Docker file for our custom Mongo client ‘seeder’.start.shwill contain the majority of the work we will have our ‘seeder’ execute as apart of itsCMDinstruction.collectionscontains the JSON files representing the seed data we want in our Mongo container.
Step 2: We will start with docker-compose.yml. Edit it so that it has the following:
- This creates our main container,
my_mongo, where our Mongo database will live: image: mongopulls the Mongo image from Docker Hubports:maps local port 27019 to port 27017 (Mongo’s default port) in the container. We pick 27019 to avoid conflicting with any Mongo already running on the host machine.environment:set environment variables for Mongo to configure the root user credentials.- (optional) To test this:
- Run
docker-compose up -din theTonicMongoDockerTutorial_startdirectory. - Connect to it using MongoDB Compass. Start a new connection. Click
Fill in connection fields individually, selectauthentication: username/password, and fill in the following parameters: - hostname:
localhost - port:
27019 - username:
root - password:
rootpassword - You should see the default databases,
admin,config, andlocal. Now let’s set it up with some seed data!
Step 3: Let’s create the Docker image for our seeder container. Edit Dockerfile so that it looks like:
- This creates our seeder container:
FROM mongopulls the Mongo image from Docker Hub; this gives the container the ability to use a Mongo client to seed the data.COPY collections/Restaurants.json /collections/Restaurants.jsoncopies the collection JSON into the seeder container.ADD start.sh /start.shadds the shell script (detailed in Step 4) into the container.RUN chmod +x /start.shmakes the script executable in the container.CMD ["/start.sh"]runs the script when the container starts.
Step 4: Let’s put the logic to seed the database in start.sh:
- This uses mongoimport to import the collection data into the
my_mongocontainer. Most of this should be self-explanatory: sleep 10waits for 10 seconds to givemy_mongoenough time to start up.--host my_mongospecifies the host name of themy_mongocontainer. Our Docker compose will make sure this resolves!--db tutorial_dbnames the database we want to put our collection in. It will auto create the DB if it does not exist.
Step 5: Now let’s tie it all together and add our seeder image to docker-compose.yml.
- We’ll add the additional service entry for our seeder container:
mongo_seederis our container name.image: mongo_seederwill be the image name for when we build our Dockerfile.depends_onmakes it so we can accessmy_mongoas a host name instart.shas mentioned in Step 4.
Step 6: Testing it all out from the TonicMongoDockerTutorial_start directory.
- Build the Dockerfile
docker build -f Dockerfile -t mongo_seeder . - Run docker-compose
docker-compose up -d - Wait for the seeder to complete, and your restaurant collection should be accessible via MongoDB Compass! (see optional part of Step 2 for connection details)
Step 7 (Bonus): Configuring users and their permissions.
- You may want to configure different users in your Mongo database with different permissions. We can add a javascript script to our Docker container to run Mongo commands to set that up!
- Create a file in
TonicMongoDockerTutorial_startdirectory with the following contents calledsetupUsers.js:
- We can connect to our database and create a role and user with only
listCollections,find, andlistDatabasesprivilege actions to theRestarauntscollection, and no privilege to theUserscollection. This should give us just enough to be able to view onlyRestaurantsdocuments, but not edit them in MongoDB Compass.
- Make sure
setupUsers.jsis copied into the container inDockerfile:
- Invoke
setupUsers.jsinstart.sh:
mongoshinvokes the Mongo shell with oursetupUsers.jsfile.- To test this, rerun Step 6, and log in with our MongoDB Compass as username:
lowAccessUser, password:lowaccessuserpasswordand see we only have access to view documents on theRestaurantscollection. setupUsers.jsdoes not have to be just for setting up users. You can do anything there that you can do in the mongo shell.
Conclusion
There we have it! Now all you have to do to reproduce your Mongo state anywhere is pull something like this from a repo onto a machine with Docker and run the commands from Step 6. You can download the complete code here: TonicMongoDockerTutorial_final.zip.
Credit to https://gist.github.com/yoobi55/5d36f13e902a75225a39a8caa5556551 for the Restaurant json data.
*** This is a Security Bloggers Network syndicated blog from Expert Insights on Synthetic Data from the Tonic.ai Blog authored by Expert Insights on Synthetic Data from the Tonic.ai Blog. Read the original post at: https://www.tonic.ai/blog/dockerizing-and-seeding-your-development-mongodb-database

