Skip to content

Instantly share code, notes, and snippets.

@haizi-zh
Created April 29, 2016 16:05
Show Gist options
  • Save haizi-zh/05d91a4324e2cb324dc555b3c2b9b7e4 to your computer and use it in GitHub Desktop.
Save haizi-zh/05d91a4324e2cb324dc555b3c2b9b7e4 to your computer and use it in GitHub Desktop.
Notes on MongoDB

To deploy our MongoDB instances, we choose to use the official Docker images: MongoDB 3.2

By inspecting into the image, we can easily find that the entry point is: /entrypoint.sh.

Setup the primary node

We need a data volume for better data persistency:

docker run --name mongo1-data -v /data/db busybox

To start a simple MongoDB instance, which doesn't support replica set and has no authentication:

docker run -it --rm --volume-from mongo1-data -p 27017:27017 mongo:latest

MongoDB uses key files for inner communication within shards and replica set clusters. Therefore, we need to generate a key file for our replica set:

openssl rand -base64 258 > /root/mongo_key

Open another terminal, connect to the Mongo Shell, and then add a root user to the admin database.

Stop the previous temporary MongoDB container, and start the formal one with full authentication and replica set:

docker run -d --name mongo1 -p 27017:27017 -v /root/mongo_key:/mongo_key mongo --repliSet default --auth --keyFile /mongo_key

Connect to the database, use rs.initiate() to initialize the node to be primary. However, there is one more step. By default, a Docker container will get a random string at creation, which will be used as its host name. This random host name will later be used as the host in rs configuration, but other containers cannot use such host name for access. So we must reconfigure it to real host names:

> var c = rs.config()
> c.members[0].host = "172.17.0.1:27017"
> rs.reconfig(c)

After setting up the primary node, we can start more MongoDB nodes and add them one by one into the replica set:

docker run -d --name mongo2 -p 27018:27017 -v /root/mongo_key:/mongo_key mongo --repliSet default --auth --keyFile /mongo_key
> rs.add("172.17.0.1:27018")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment