How to start a mongodb shell in docker container?

MongodbDocker

Mongodb Problem Overview


To start the container, I am typing the following command:

sudo docker run -i -t -p 28000:27017 mongo:latest /usr/bin/mongod --smallfiles

But I want to open the shell in this container to type the mongo commands. What command should I run to do the same?

Mongodb Solutions


Solution 1 - Mongodb

You can run the interactive mongo shell by running the following command:

docker run -it -p 28000:27017 --name mongoContainer mongo:latest mongo

Otherwise, if your container is already running, you can use the exec command:

docker exec -it mongoContainer mongo

Solution 2 - Mongodb

The thing that I struggled too but found a solution:

docker pull mongo
docker run --name CONTAINERNAME --restart=always -d -p 8080:8080 mongo mongod --auth
sudo docker exec -i -t CONTAINERNAME bash
mongo
use admin
db.createUser({user:"user", pwd:"password", roles:[{role:"root", db:"admin"}]})
exit && exit

Now you have created a running Docker container with everything you need. Now if you want to connect from any client with an admin user, just run this

mongo -u "user" -p "password" HOSTIP --authenticationDatabase "admin"

Solution 3 - Mongodb

Download the latest MongoDB Docker image from Docker Hub

sudo docker pull mongo

Now set up MongoDB container

docker run --name containername mongo

Interact with the database through the bash shell client

docker exec -it containername bash

Launch the MongoDB shell client

mongo

Solution 4 - Mongodb

Extending and updating @vladzam answer and if your container is already running in docker, you can use the exec mongosh command with login and pass options like this:

docker exec -it database-dev mongosh -u "myLogin" -p "myPass"

Solution 5 - Mongodb

Assuming you have mongo installed on your host computer, which was in my case when I asked this question years ago. This is an alternate way I tried: Open a new terminal

mongo 127.0.0.1:28000

Your mongo shell starts in this terminal now.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMadhavi JouhariView Question on Stackoverflow
Solution 1 - MongodbvladzamView Answer on Stackoverflow
Solution 2 - MongodbAleksandr KrasnovView Answer on Stackoverflow
Solution 3 - MongodbAman RathodView Answer on Stackoverflow
Solution 4 - MongodbRomanView Answer on Stackoverflow
Solution 5 - MongodbMadhavi JouhariView Answer on Stackoverflow