Docker MongoDB Multiple Databases

Video Tutorial
Check Also
In this article, We will explain you how to set up mongDB following multiple databases using Docker-Compose
Github Repo: https://github.com/oxlb/docker-mongoDB-multiple-databases
Production Env:
The production database environment.
Development Env:
A dedicated environment for database development.
Test Env:
A dedicated environment for database testing.
Why we need multiple databases?
If you have only a Production Database and you are developing a new feature if something breaks it will affect the whole Production Database.
For best practice, You must have a different Database Development Environment because if you are developing a new feature in a Development Environment if something breaks it will not impact on Production Database Environment.
Let’s Start Creating Multiple Environment Databasez
Hope you are familiar with “Docker-Compose”
Folder structure
Project
├── docker-compose.yml (File)
├── docker-entrypoint-initdb.d (Directory)
│ ├── mongo-init.js (File)

Create a new file docker-compose.yml
Above file, we have created mongoDB Docker container with Port No: 27017
As well as set environment variables such as default username, password of mongoDB container.
if you check the entire file we have also created volumes that point to the `mongo-init.js` file.
./docker-entrypoint-initdb.d/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
The script inside “mongo-init.js” will create multiple databases upon container startup. You can see the following file we have created 3 database and 3 different users for each database.
- api_prod_db (For Production Use)
- api_dev_db (For Development)
- api_test_db (For Testing)
When you run the following command in the root directory for the project.
docker-compose up
then you will see in the console mongo-init.js script will be executed as the following screenshot

that means your script executed successfully.
How to test connection
For testing, we used Robo 3T you can download from here and install it.
then open the Robo 3T click on Create link which shows a top right side of the popup as shown in the following screenshot.

Then you will see another pop up as the following screenshot.

In the Connection tab, You can type the name of the connection.
We have typed Dev DB as shown in the above screenshot.
Click on the Authentication tab then type the user credential that we have created in the mongo-init.js file
Following screenshot, We are using api_dev_db database( For Development purpose)

then click on the test button shown in the above screenshot. then it will show you whether a connection is failed or pass as shown below.

Conclusion
For the best practice, You must have multiple environments for your Database, App, etc.