DEV Community

Rafael Ahrons
Rafael Ahrons

Posted on • Originally published at luturol.github.io

Using MongoDB with Docker

Using MongoDB with Docker

What you need to have installed:

  • Docker

With you want to learn more about Docker, you can check my blog post about it by clicking here

Downloading MongoDB Image

docker image pull mongo
Enter fullscreen mode Exit fullscreen mode

Run a container

docker run -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=root -p 27017:27017 mongo
Enter fullscreen mode Exit fullscreen mode

Change password and username for a suitable for you

What this command does

It will initialize your container and show you the logs while is initializing, so you can track if some errors appear in the console log.

-e will add MONGO_INITDB_ROOT_USERNAME environment variable with the value root. With that, your username to connect will be root.

-e will add MONGO_INITDB_ROOT_PASSWORD environment variable with the value root. With that, your password to connect will be root.

-p will share your local port with the port of the container. 27017 is the port that mongodb use.

Executing the same mongodb container after ended

  1. You need to get the container ID from your mongodb container.

    docker container ps -a
    
  2. With the container Id, now you can enter using the following command:

    docker start containerId
    

    It will enter inside the container with a bash terminal executing.

Testing your connection

  1. Testing your connection

    You must have some program to connect with MongoDB. You can use or Mongo Compass or Robot3 or the one you prefer.

    To connect you will need a connection string.

    mongodb://root:root@localhost:27017/admin
    

    This is the connection string to connect inside mongodb of our container.

What does that connection string means:

  1. First root is the username (if you changed, you must change in the connection string as well)

  2. Second root is our password (if you changed, you must change in the connection string as well)

  3. After @ is the IP you are trying to connect and the database that holds your user.

References

Top comments (0)