This write-up will explain the method to run a MongoDB server with Docker Compose.
How to Run a MongoDB Server with Docker Compose?
To run a MongoDB server with Docker, Compose, try out the below-mentioned steps:
- Create Compose file and set MongoDB services
- Start the Compose services
- View running MongoDB container
- Access MongoDB container
- Verify MongoDB server
- Connect to MongoDB server
- Run MongoDB commands
Step 1: Create Compose File
First, create a “docker-compose.yml” file on Visual Studio Code and paste the below-provided snippet into it:
image: mongo:latest //defining Docker image
container_name: mongoDB-Cont //specifying container name
- 27017:27017 //assigning port
In the above code:
- “version” defines the version of the Docker Compose file. In our case, it is “3.7”.
- “services” specifies the services that are required to be run with Docker Compose.
- “mongodb-Cont” is the name of the MongoDB service.
- “image” defines the image to use i.e., “mongo:latest”.
- “container_name” defines the name of the container i.e., “mongoDB-Cont”.
- “environment” sets environment variables for the MongoDB container such as username and root password.
- “ports” is utilized to assign port i.e., “27017:27017”
- “volumes” set up a volume named “mongodb_data_cont” to persist the MongoDB data:
Step 2: Start the Compose Service
Then, start the MongoDB services defined in the compose file by executing the given command:
This command starts the MongoDB server.
Step 3: View Running MongoDB Container
After that, write out the below-stated command to view the running MongoDB container:
According to the above screenshot, the MongoDB container is successfully running.
Step 4: Access MongoDB Container
Next, open the Bash shell inside the running MongoDB container through the following command:
Step 5: Verify MongoDB Server
Execute the given command to ensure that the MongoDB server is running or not:
The above output indicates that the MongoDB server is running successfully with version “v6.0.5”.
Step 6: Connect to MongoDB Server
Now, connect to the MongoDB server by utilizing the below-listed command and enter the password:
It can be seen that the MongoDB shell has been started.
Step 7: Execute MySQL Commands
Finally, run the MongoDB commands in the MongoDB container. For instance, execute the “show dbs” command to view all the existing databases:
The above output has displayed all the existing databases.
To run a MongoDB server with Docker, first, create a Compose file and define the MongoDB services. Then, start to Compose services via the “docker-compose up -d” command and view the running container. After that, access the MongoDB container and connect to the MongoDB server. Finally, run MongoDB commands in it. This article has demonstrated the method to run a MongoDB server with Docker Compose.