Mongo DB on Docker


MongoDB on Docker

Command

docker run --name mongo -d -p 27017:27017 -v /my/own/datadir:/data/db mongo

Port

27017 is mongo port. Hence exposing the same to our local.

Volume

 -v creates a volume and ties a local folder /my/own/datadir to the container. So even if container is destroyed, data stays. This data can help us re-create a new mongo container with same data. You can omit -v if you want to create a fresh mongo container.

Securing mongo

We can have username and password to secure mongo instance. This can be set when creating mongo container as below

 

docker run --name mongo -d \
-p 27017:27017 \
-v /my/own/datadir:/data/db \
-e MONGO_INITDB_ROOT_USERNAME=mongoadmin \
-e MONGO_INITDB_ROOT_PASSWORD=secret \
mongo
And then when in command shell after exec
mongo -u mongoadmin -p secret

Testing

Use the following command to enter running docker container shell and execute commands
docker exec -ti mongo sh

Once we have access, we can use mongo command shell to execute our commands

mongo 

This command starts a mongo command shell.

show dbs

Use this command to list all the DBs currently available.

Further information

Further information about official mongo image can be found at https://hub.docker.com/_/mongo.


Comments