how to use mongo docker image

·

3 min read

What is Docker:

Docker is a popular open-source project works as a container engine that uses the Linux Kernel features like namespaces and control groups to create containers on top of an operating system. By using docker we can package our applications into container.

What are the benefits of using mongodb docker image locally

The main benefits of using mongo docker image locally we don't need to download and install mongodb in our local machine. We can perform all mongodb operations using docker image.

To use docker we need Docker installed in our system from the following link: Docker installation step by step guide

Our First step is to visit docker hub website

Docker hub website

search for mongo in the search bar, we will find mongo repository. our first command is to pull mongo docker image

docker pull mongo

If we want to pull any specific image version of mongo we will have to execute below command

docker pull mongo:version

Our next step is to create docker network

docker network create mongo-network

Before executing above command please check any existing network is not running with the same name. Below command will list all the running networks

docker network ls

Now execute below command to start mongo container with the downloaded mongodb image

docker run -p 27017:27017 -d -e MONGO_INITDB_ROOT_USERNAME=ashish -e MONGO_INITDB_ROOT_PASSWORD=ashish --name mongodb --net mongo-network mongo
  • -p means port allocating to the container
  • -d means in a reattached mode we are starting docker container
  • -e means we are setting username/password globally
  • mongo-network is the network we have created previously using network create command
  • at last mongo is a image we pull previously using docker pull command

execute below command in case we don't want to connect our application with username/password

docker run -p 27017:27017 -d --name mongodb --net mongo-network mongo

Now the next step is to connect our node/express applications with mongodb container.

  • first step is to download mongoose in our application

use below command in case we are running container with username/password. dbname is a database name will create on the fly

mongoose.connect('mongodb://ashish:ashish@localhost:27017/dbname');

use below command in case we are running container without username/password

mongoose.connect('mongodb://localhost:27017/dbname');