Running two MongoDB instances on one server

 
Published on 2016-04-28 by John Collins. Socials: YouTube - X - Spotify - Amazon Music - Apple Podcast

Introduction

As I am presently learning about MongoDB, I wanted to get some practice with the sharding and replication features of the database, which would require access to at least two running instances of MongoDB. Rather than running two seperate machines or doing something with virtualization, I wanted to keep it simple and get two instances running locally on my Fedora laptop. Here are the steps that I followed to get this working.

Note that this tutorial assumes you already have one instance of MongoDB already installed, see my guide here for instructions on that.

1. Make a copy of the MongoDB config file for the second instance

$ cp /etc/mongod.conf /etc/mongod2.conf

2. Edit the second file to have different paths and port

$ nano /etc/mongod2.conf

You should change the file paths for the database storage directory, the log directory, and the port on which the second instance of MongoDB will run, to ensure it does not interfere with the first instance.

3. Copy the init.d script and make some changes

$ cp /etc/init.d/mongodb /etc/init.d/mongodb2

Now edit the /etc/init.d/mongodb2 script, and make the following changes:

...
CONFIGFILE="/etc/mongod2.conf"
...
mongod=${MONGOD-/usr/bin/mongo2}

In the same file you should also replace all instances of /var/lock/subsys/mongod with /var/lock/subsys/mongod2.

4. Copy the mongod binary for the second instance

$ cp /usr/bin/mongod /usr/bin/mongod2

5. Create some required directories for the second MongoDB instance

These values should match up with whatever you have in your /etc/mongod2.conf and /etc/init.d/mongodb2 files.

$ mkdir /var/log/mongodb2
$ chown mongo:mongo /var/log/mongodb2
$ mkdir /var/lib/mongodb2
$ chown mongo:mongo /var/lib/mongodb2
$ mkdir /var/run/mongodb2
$ chown mongo:mongo /var/run/mongodb2

Conclusion

If everything works as expected, you should now be able to use the following commands to start/stop both MongoDB instances, or connect to either using the mongo client and the port flag:

$ service mongod[2] start|stop|status
$ mongo --port [port]