Techscrypt

How to setup a MongoDB database in Docker

mongodbdocker

Why you should run databases in docker for local development

Installing and maintaining a local version of a database can take up a lot of valuable time. Setting up a database in docker can help save that time, and make the the installation a lot more portable, since docker containers can be moved around.

If you have multiple applications that need different versions of MongoDB on your local machine, then running each of them in a docker container can make it a trivial task.

If you are new to docker, read up here — https://www.docker.com/products/docker-desktop. Assuming you have docker setup on your machine, following steps illustrate how to setup a MongoDB database in a docker container

Create a container running MongoDB

docker run -p <host_machine_port>:27017 --name <container_name> -e MONGO_INITDB_ROOT_USERNAME=<root_username> -e MONGO_INITDB_ROOT_PASSWORD=<root_password> -d mongo:<version>

Let us look at all the parameters in the above command

<host_machine_port> — The port on your local machine that you want the container connected to. For example, if you want the mongo instance on localhost:3310, your <host_machine_port> would be 3310

<container_name> — The name of the container that will be created

<root_username> — The username for the root user on the mongo instance.

<root_password> — The password for the root user on the mongo instance.

<version> — The version of MongoDB that you want to run

For example, if you want to create a MongoDB instance using the latest version of MongoDB with a database called people with a root password = my_password connected to your local machine port 3310, the following command would accomplish that.

docker run -p 3310:27017 --name mongo_db_instance -e MONGO_INITDB_ROOT_USERNAME=mongorootuser -e MONGO_INITDB_ROOT_PASSWORD=mongopassword -d mongo

Verify container status using this command

docker container ls

The above command will display all the docker containers running on your machine, and you should see your newly created container.

Connect to the database instance

Now you can connect to the mongo database instance using the mongo command if you have it installed on your local machine. But given the fact that we did not want to install mongo on our local machine in the first place, it would be better if we connect to the database using shell access inside the container.

Get shell access inside the docker container using

docker exec -it <container_name> bash

And then run mongo command inside the container to connect to the database.

References

  1. MongoDB Docker
  2. Docker Desktop

Subscribe to the Newsletter

We will only use your email address to send out the weekly newsletter with the latest updates from Techscrypt.

* indicates required