MongoDB Tutorial 4 [Create MongoDB Database using Docker Compose]

MongoDB Tutorial 4 [Create MongoDB Database using Docker Compose]

In this tutorial, we will learn about “How to create MongoDB Database using Docker Compose“. This guide walks you through the step-by-step process of creating a MongoDB instance within a Docker container, leveraging the power and flexibility of Docker Compose to streamline deployment and management. From configuring the Docker Compose YAML file to initializing the MongoDB database, this tutorial will provide you the knowledge to swiftly deploy MongoDB for your learning and development needs. So, let us begin the tutorial.

 

What is Docker Compose?

Also Read: MongoDB Tutorial 1 [How to Install MongoDB on Windows]

Docker Compose is a tool for defining and running multi-container Docker applications. It allows to define the application’s services, networks, and volumes in a single file, typically named as docker-compose.yml. With Docker Compose, you can easily manage the lifecycle of an application’s containers, including starting, stopping, and rebuilding them.

The docker-compose.yml file specifies the configuration for your application’s services, including the Docker images to use, environment variables, network settings, volumes to mount, and other options. Docker Compose then uses this configuration to create and manage the containers for your application.

Using Docker Compose simplifies the process of deploying and managing complex applications that consist of multiple interconnected containers. It abstracts away much of the complexity of orchestrating these containers, making it easier to develop, test, and deploy containerized applications.

 

MongoDB Tutorial 4 [Create MongoDB Database using Docker Compose]

If you have not yet gone through my previous tutorials on MongoDB, I recommend you to go through the tutorials from here to get better understanding to this tutorial.

Prerequisite

  • Docker Installed.
  • Docker-compose Installed.
  • Basic understanding of docker commands.
  • Any IDE (I am using VS Code)
  • Git Installed.

 

NOTE:

 To demonstrate this tutorial, I have used Windows operating system. I have also installed Git as it by default comes with bash shell (Git bash) which helps to executing the Linux CLI commands easily on Windows. This step is optional, you can also use PowerShell which is default terminal on Windows systems.

 

Step-1: Pull MongoDB Docker Image

This is the first step where we will pull the mongodb docker image from hub.docker.com using the cli command docker pull mongo <tag>. If you do not specify the tag in the command, it will pull the latest image as shown below.

[email protected]$ docker pull mongo
Using default tag: latest
latest: Pulling from library/mongo
bccd10f490ab: Pull complete
93f07c832c0f: Pull complete
dab2da22865c: Pull complete
1f7ceac81d5b: Pull complete
3e507bb35e33: Pull complete
bf53d03cb40e: Pull complete
cc32baa6c25a: Pull complete
15cbd2791748: Pull complete
Digest: sha256:019bf5423a08363f253d81a3f16cc6527e7342a7f5420a5ad74663cc2c62d0e7
Status: Downloaded newer image for mongo:latest
docker.io/library/mongo:latets

 

Next, check if image is pulled successfully by executing the command docker images which will list all the pulled docker images so far as shown below.

[email protected]$ docker images
REPOSITORY TAG    IMAGE ID     CREATED     SIZE
mongo      latest 79112eff9c89 2 weeks ago 756MB

 

Step-2: Create Docker Compose File

In this step, once the mongo Docker image is pulled, we will use this image in docker compose file. So create a docker compose file in which we will add the configuration for creating mongodb container. Create a new file called  docker-compose.yml. Once the file is created,  add below content to it. Once done, save the file and exit from the file.

version: "23.3"
services:
  mongodb:
    image: mongo
    container_name: mongodb
    environment:
      - PUID=1000
      - PGIU=1000
    volumes:
      - "D:/go-project/mongo-database:/data/db"
    ports:
      - 27017:27017
    restart: "unless-stopped"
Code Explanation
  1. version: “23.3”: This specifies the version of the Docker Compose file syntax being used. In this case, it’s version 23.3.
  2. services: This section defines the different services that will be run by Docker.
  3. mongodb:  This is the name of the service being defined. It will run a MongoDB database server.
  4. image: mongo: This specifies the Docker image to be used for this service. In this case, it will pull the official MongoDB image from Docker Hub.
  5. container_name: mongodb: This sets the name of the container running the MongoDB service to “mongodb”.
  6. environment:  This section allows you to set environment variables for the container. In this case, it sets the PUID (Process User ID) and PGID (Process Group ID) to 1000. This is often done to ensure that the process inside the container runs with specific user and group permissions.
  7. volumes: This section defines volumes to be mounted inside the container. In this case, it mounts the directory “D:/go-project/mongo-database” on the host machine to the “/data/db” directory inside the container. This is done to persist the data stored by MongoDB even if the container is stopped or removed.
  8. ports: This section maps ports from the host machine to the container. In this case, it maps port 27017 on the host to port 27017 on the container. This allows external applications to communicate with the MongoDB server running inside the container.
  9. restart: “unless-stopped”: This specifies the restart policy for the container. In this case, it will automatically restart the container unless it has been explicitly stopped by the user.

 

Step-3: Execute Docker Compose Script

In this step, switch to the directory where you have created and stored the docker-compose.yml file. Then execute the file using command docker-compose -f <compose-file-path> up -d. This will execute each line of code in the provided docker-compose.yml file and create the container as shown below.
Before executing the compose file, you will notice that there is only one file present in the current directory which is docker-compose.yml file itself. After the container is created, it will generate some new files in the mounted path which we will see in next step.

[email protected]$ ls
docker-compose.yaml

 

Next, create the container by executing the docker-compose.yml file.

[email protected]$ docker-compose -f /d/go-project/mongo-database/docker-compose.yml up -d
[+] Running 1/1
✔ Container mongodb Started

 

Next, check if the container is created successfully using below command.

[email protected]$ docker ps
CONTAINER ID  IMAGE   COMMAND                CREATED        STATUS        PORTS                    NAMES
d9f220ca865a  mongo   "docker-entrypoint.s…" 48 seconds ago Up 46 seconds 0.0.0.0:27017->27017/tcp mongodb

 

After the container is created, list the files again in current directory as shown below,

[email protected]$ ls -lhtr
-rw-r--r-- 1 coder 197609 268 Mar 17 12:13 docker-compose.yml
-rw-r--r-- 1 coder 197609 21 Mar 17 13:55 WiredTiger.lock
-rw-r--r-- 1 coder 197609 50 Mar 17 13:55 WiredTiger
-rw-r--r-- 1 coder 197609 114 Mar 17 13:55 storage.bson
-rw-r--r-- 1 coder 197609 32K Mar 17 14:15 index-8--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 64K Mar 17 14:15 collection-7--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 20K Mar 17 14:16 index-10--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 112K Mar 17 14:16 collection-9--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 32K Mar 17 14:17 index-12--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 9.2M Mar 17 14:17 collection-11--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 36K Mar 17 15:58 collection-4--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 12K Mar 17 16:03 index-5--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 4.0K Mar 17 14:15 WiredTigerHS.wt
-rw-r--r-- 1 coder 197609 36K Mar 17 14:15 _mdb_catalog.wt
-rw-r--r-- 1 coder 197609 2 Mar 17 14:15 mongod.lock
-rw-r--r-- 1 coder 197609 92K Mar 17 14:21 WiredTiger.wt
-rw-r--r-- 1 coder 197609 1.5K Mar 17 14:21 WiredTiger.turtle
drwxr-xr-x 1 coder 197609 0 Mar 17 14:22 diagnostic.data/

 

Step-4: Login to Mongodb Container

In this step, after the container is created successfully, login to the container using below command. Since we have configured the UID as 1000 in the docker-compose.yml file, it will login as root user inside the container.

[email protected]$ docker exec -it mongodb bash
root@d9f220ca865a:/#

 

Next, switch to the path /data/db inside the container. You will see that all the files in your local system is also present in this path as shown below.

root@d9f220ca865a:/# cd /data/db/
root@d9f220ca865a:~# ls -lhtr
-rw------- 1 mongodb mongodb 50 Mar 17 08:25 WiredTiger
-rw------- 1 mongodb mongodb 21 Mar 17 08:25 WiredTiger.lock
-rw------- 1 mongodb mongodb 9646080 Mar 17 08:47 collection-11--5563902724442091128.wt
-rw------- 1 mongodb mongodb 36864 Mar 17 10:28 collection-4--5563902724442091128.wt
-rw------- 1 mongodb mongodb 65536 Mar 17 08:45 collection-7--5563902724442091128.wt
-rw------- 1 mongodb mongodb 114688 Mar 17 08:46 collection-9--5563902724442091128.wt
-rw------- 1 mongodb mongodb 20480 Mar 17 08:46 index-10--5563902724442091128.wt
-rw------- 1 mongodb mongodb 32768 Mar 17 08:47 index-12--5563902724442091128.wt
-rw------- 1 mongodb mongodb 12288 Mar 17 10:33 index-5--5563902724442091128.wt
-rw------- 1 mongodb mongodb 32768 Mar 17 08:45 index-8--5563902724442091128.wt
drwx------ 1 mongodb mongodb 4096 Mar 17 08:46 journal
-rwxrwxrwx 1 mongodb root 268 Mar 17 06:43 docker-compose.yml
-rw------- 1 mongodb mongodb 2 Mar 17 08:45 mongod.lock
-rw------- 1 mongodb mongodb 114 Mar 17 08:25 storage.bson

 

Step-5: Mount Database in Container

In this step, let us create a database in local system in the path where container volume is mounted. I am using sample_analytics database from here.

[email protected]$ ls -lhtr
-rw-r--r-- 1 coder 197609 268 Mar 17 12:13 docker-compose.yml
-rw-r--r-- 1 coder 197609 21 Mar 17 13:55 WiredTiger.lock
-rw-r--r-- 1 coder 197609 50 Mar 17 13:55 WiredTiger
-rw-r--r-- 1 coder 197609 114 Mar 17 13:55 storage.bson
drwxr-xr-x 1 coder 197609 0 Mar 17 14:07 sample_analytics/
-rw-r--r-- 1 coder 197609 32K Mar 17 14:15 index-8--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 64K Mar 17 14:15 collection-7--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 20K Mar 17 14:16 index-10--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 112K Mar 17 14:16 collection-9--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 32K Mar 17 14:17 index-12--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 9.2M Mar 17 14:17 collection-11--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 36K Mar 17 15:58 collection-4--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 12K Mar 17 16:03 index-5--5563902724442091128.wt
-rw-r--r-- 1 coder 197609 4.0K Mar 23 14:15 WiredTigerHS.wt
-rw-r--r-- 1 coder 197609 36K Mar 23 14:15 _mdb_catalog.wt
-rw-r--r-- 1 coder 197609 2 Mar 23 14:15 mongod.lock
drwxr-xr-x 1 coder 197609 0 Mar 23 14:16 journal/
drwxr-xr-x 1 coder 197609 0 Mar 23 14:22 diagnostic.data/

 

If you check the the /data/db  path inside the container, this database will be present as we have mounted the volume as shown below.

root@d9f220ca865a:~# ls -lhtr
-rw------- 1 mongodb mongodb 50 Mar 17 08:25 WiredTiger
-rw------- 1 mongodb mongodb 21 Mar 17 08:25 WiredTiger.lock
-rw------- 1 mongodb mongodb 9646080 Mar 17 08:47 collection-11--5563902724442091128.wt
-rw------- 1 mongodb mongodb 36864 Mar 17 10:28 collection-4--5563902724442091128.wt
-rw------- 1 mongodb mongodb 65536 Mar 17 08:45 collection-7--5563902724442091128.wt
-rw------- 1 mongodb mongodb 114688 Mar 17 08:46 collection-9--5563902724442091128.wt
-rw------- 1 mongodb mongodb 20480 Mar 17 08:46 index-10--5563902724442091128.wt
-rw------- 1 mongodb mongodb 32768 Mar 17 08:47 index-12--5563902724442091128.wt
-rw------- 1 mongodb mongodb 12288 Mar 17 10:33 index-5--5563902724442091128.wt
-rw------- 1 mongodb mongodb 32768 Mar 17 08:45 index-8--5563902724442091128.wt
drwx------ 1 mongodb mongodb 4096 Mar 17 08:46 journal
-rwxrwxrwx 1 mongodb root 268 Mar 17 06:43 docker-compose.yml
-rw------- 1 mongodb mongodb 2 Mar 17 08:45 mongod.lock
drwxrwxrwx 1 mongodb root 4096 Mar 17 08:37 sample_analytics
-rw------- 1 mongodb mongodb 114 Mar 17 08:25 storage.bson

 

Step-6: Import MongoDB Database

After the database is mounted inside the container, we will now import the database. Switch to the folder sample_analytics. You will notice that there are few json files present inside this folder as shown below.

root@d9f220ca865a:~# cd sample_analytics/
root@d9f220ca865a:~/sample_analytics# ls
accounts.json customers.json transactions.json

 

Next, execute below commands to import each database present inside sample_analytics folder as shown below.

root@d9f220ca865a:~/sample_analytics# mongoimport accounts.json -d sample_analytics -c accounts --drop
2024-03-17T08:45:27.292+0000 connected to: mongodb://localhost/
2024-03-17T08:45:27.293+0000 dropping: sample_analytics.accounts
2024-03-17T08:45:27.393+0000 1746 document(s) imported successfully. 0 document(s) failed to import.
root@d9f220ca865a:~/sample_analytics# mongoimport customers.json -d sample_analytics -c customers --drop
2024-03-17T08:46:14.369+0000 connected to: mongodb://localhost/
2024-03-17T08:46:14.370+0000 dropping: sample_analytics.customers
2024-03-17T08:46:14.454+0000 500 document(s) imported successfully. 0 document(s) failed to import.
root@d9f220ca865a:~/sample_analytics# mongoimport transactions.json -d sample_analytics -c transactions --drop
2024-03-17T08:46:47.968+0000 connected to: mongodb://localhost/
2024-03-17T08:46:47.968+0000 dropping: sample_analytics.transactions
2024-03-17T08:46:48.608+0000 1746 document(s) imported successfully. 0 document(s) failed to import.

 

Next, exit from the container and re-login using below command to open the mongo shell.

[email protected]$ docker exec -it mongodb mongosh bash
Current Mongosh Log ID: 65f6af8bd321146b9e1a6bcf
Connecting to: mongodb://127.0.0.1:27017/bash?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.1.5
Using MongoDB: 7.0.6
Using Mongosh: 2.1.5

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.

------
The server generated these startup warnings when booting
2024-03-17T08:25:36.667+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
2024-03-17T08:25:36.668+00:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
2024-03-17T08:25:36.668+00:00: vm.max_map_count is too low
------

bash>

 

Next, to see the databases inside the container, execute the command show databases as shown below.

bash> show databases
admin 40.00 KiB
config 60.00 KiB
local 40.00 KiB
sample_analytics 9.45 MiB

 

Next, switch to the database, sample_analytics

bash> use sample_analytics
switched to db sample_analytics

 

Next, list the collections in this database.

sample_analytics> show collections
accounts
customers
transactions

 

Next, run a simple query against any collection just to make sure they are working fine. I am executing the query to find all the records in collection “accounts” where limit is equal to 9000 using below query command.

sample_analytics> db.accounts.find({limit: 9000})

[
{
_id: ObjectId('5ca4bbc7a2dd94ee58162392'),
account_id: 794875,
limit: 9000,
products: [ 'InvestmentFund', 'InvestmentStock' ]
},
.........................................................................

.........................................................................
{
_id: ObjectId('5ca4bbc7a2dd94ee58162754'),
account_id: 853387,
limit: 9000,
products: [ 'Derivatives', 'InvestmentStock' ]
}
]

The above command output will return all the records where limit is set to 9000.

 

Step-7: Exit From Mongodb Container

To exit from the mongodb container, type the command exit. It will bring you back to the terminal.

sample_analytics> exit
[email protected]$

 

Summary

We have successfully created the Mongodb docker container using the docker-compose script. We have also mounted the volume inside the container and created the database and few collections inside the database. We have also verified the working of collection using a simple query to find the records in a collection.

Leave a Comment