Setting up a Mongodb replicaset in docker-compose with Hidden Members


This is for instructional purposes, obviously in a production environment you would not run multiple mongodb databases on the same host as this will dramatically increase the load on the server as well as providing no redundancy in the event of the host going down.


sudo docker-compose up -d


  • To create the replicaset, use the mongo command to access mongodb1 on port 27017 and use rs.initiate to create the replicaset (Adjusting the initiate command based on how many mongodb instances you require).

NOTE: If you do not have mongo client installed on your Desktop, you can docker exec into the container to run the below.


rs.initiate( {
_id : "test",
members: [
{ _id: 0, host: "mongodb1:27017" },
{ _id: 1, host: "mongodb2:27018" },
{ _id: 2, host: "mongodb3:27019" },

You can confirm the replicaset status by running the below:



Adding a Replica set member

To add a new member to your cluster, run the below command from one of the existing database servers (Will be using mongodb4 for this example):.


rs.add( { host: "mongodb4:27020", priority: 0, votes: 0 } )

Making a “Hidden” Replicaset member

To add a hidden member to your Mongodb cluster (Eg for backups) add the new member to the cluster and set it’s attribute to hidden as below (Will be using mongodb5 for this example):


rs.add( { host: "mongodb5:27021", priority: 0, votes: 0 } )

Now use rs.status() to get the “id” of the new replicaset member – Make a note of this _id:



Now edit the replicaset configuration to set this new member to “hidden”, replacing id with the value you noted before (Eg 4)

cfg = rs.conf()
cfg.members[4].priority = 0
cfg.members[4].hidden = true

Any comments or questions? Get in touch here or Email me at [email protected]