Setting up a local MongoDB replica set with a single node

Nikolay Mihaylov
2 min readJun 16, 2023

If you want to use some MongoDB features you need a DB running as a replica set. This would usually be the case on a production server, but to run it locally you need to make some changes.

According to MongoDB:

A replica set in MongoDB is a group of mongod processes that maintain the same data set. Replica sets provide redundancy and high availability, and are the basis for all production deployments.

Unlike a standalone instance, a MongoDB replica set supports features like transactions. For a local dev environment, you wouldn’t really need a replica set with several nodes, that’s why this article describes how to configure a local replica set with a single node.

There are two things that need to happen to have your replica set:

  • Step 1: Define your node(s) as part of a replica set
  • Step 2: Initiate the replica set

The first step happens when you start up your MongoDB server, whereas the second step can be triggered at a later stage. First of all, let’s define our database in a docker-compose.yml:

By passing the parameters on line 12 we instruct the Mongo instance, that it’s part of a replica set named dbrs and that it should bind all IP addresses. To initiate the replica set (Step 2) the docker-compose file points to rs-initiate.js on line 9. It holds only a single line of code and looks like this:

Et voilà, now you can start your local replica set with the following command:

docker-compose -f docker-compose.yml up --build

Bonus

If you want to just quickly spin up a local replica set you might not need the whole docker-compose setup. Here is a handy oneliner to basically do the same thing in one go:

docker run --rm -d -p 27017:27017 -h $(hostname) --name mongo mongo:6.0.5 --replSet=dbrs && sleep 5 && docker exec mongo mongosh --quiet --eval "rs.initiate();"

--

--