Creating MongoDB instance using Docker

MongoDB can be installed and run within a docker container with its port=27017 dbpath=/data/db for storage. The docker run can start the process in the container and attach the console to the process’s standard input, output, and standard error. It can even pretend to be a TTY (this is what most command line executables expect) and pass along signals. All of that is configurable:

-a=[] : Attach to `STDIN`, `STDOUT`and/or`STDERR`
-t : Allocate a pseudo-tty
--sig-proxy=true: Proxy all received signals to the process (non-TTY mode only)
-i : Keep STDIN open even ifnot attached
  • Verify that you have docker installed run :
docker -v

,which should output the version number. Next, we need to make sure our docker daemon is running. So run :

docker images

,which should output the list of images you currently have on your system.
Next, we will get the latest version of the official Mongo image, by running

docker pull mongo
  • Find the name assigned to the MongoDB docker container. In this case: jolly_aryabhata
docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
4fba4598637a        mongo:latest        "/ /usr/"   4 minutes ago       Up 4 minutes>27017/tcp   jolly_aryabhata

  • Run the Mongo Daemon:docker run -i -t -p 27017:27017 mongo:latest /usr/bin/mongod --smallfiles2016-11-15T23:49:31.741+0000 I CONTROL [initandlisten] MongoDB starting : pid=1 port=27017 dbpath=/data/db 64-bit host=4fba4598637a
    2016-11-15T23:49:31.742+0000 I CONTROL [initandlisten] db version v3.2.10
  • Add the Initial Admin User

docker exec -it jolly_aryabhata mongo admin

connecting to: admin

> db.createUser({ user: 'jsmith', pwd: 'some-initial-password', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });Successfully added user: { "user" : "jsmith", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }

  • Run the mongo shell (

docker exec -it jolly_aryabhata mongo admin

MongoDB shell version: 3.2.10
connecting to: admin

  • MongoDB instances can be clustered within Docker on different ports using

docker network create my-mongo-cluster

  • And then starting MongoDB instances with

To start up our first container, mongo1 run the command:

$ docker run \ -p 30001:27017 \ --name mongo1 \ --net my-mongo-cluster \ mongo mongod --replSet my-mongo-set



admin has written 55 articles