In this article, We will explain you how to set up mongDB following multiple environments using Docker-Compose
The production environment.
A dedicated environment for development.
A dedicated environment for testing.
Why we need multiple environments?
If you have only a Production Environment and you are developing a new feature if something breaks it will affect the whole Production Environment.
For best practice, You must have a Development Environment because if you are developing a new feature in a Development Environment if something breaks it will not impact on Production Environment.
Let’s Start Creating Multiple Environment
Hope you are familiar with “Docker-Compose”
├── 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.
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.
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
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.
For the best practice, You must have multiple environments for your Database, App, etc.