The only prerequisite is to have 3 working Docker server. This means you can bring up a local Vagrant box with Docker installed, use CoreOS, instance on AWS, or however you like to get 3 Docker server.

Steps

Step 1: Get the IP address of all three servers and export the following IP addresses variables on all servers by running the following commands on all servers (replace the IP addresses).

Ideally you would not have and the IPs can be resolved via DNS. Since this is a test setup, this is easier.

The “—keyFile” path is “/opt/keyfile/mongodb-keyfile”. This is correct. This is the path to the key file inside the Docker container. We mapped the key file with the “-v” option to this location inside the container.

The “—add-host” adds these entries into the Docker container’s /etc/hosts file so we can use hostnames instead of IP addresses. In a production environment where these entries are in DNS, these parameters are not needed.

Step 6: Connect to the replica set and configure it. This is still on node1. We will start another interactive shell into the mongo container and start a mongo shell.

You can view what is happening in each mongo Docker container by looking at the logs. You can do this by running this command on any of the servers.

root@node*:/# docker logs -ft mongo

Conclusion

Now you have a working MongoDB cluster in a replica set. You are free to add nodes to this cluster at any time. You can even stop one of the nodes or primary node and watch another node take over as the new primary. Since the data is written to the local file system, restarting any of these nodes is not a problem. The data will persist and rejoin the cluster perfectly fine.