DEV Community

Cover image for Set up MongoDB primary and secondary with Docker.
prakash chokalingam
prakash chokalingam

Posted on

Set up MongoDB primary and secondary with Docker.

MongoDB is a popular choice for developers today when it comes to NoSQL databases. The MongoDB Community Edition is readily available as a Docker image.

To enable MongoDB transactional queries, you need to configure a replica set with primary and secondary database connections.

In this post, we’ll walk through how to set up MongoDB’s primary and secondary nodes and configure a replica set using a single docker-compose file.

Prerequisites for Running the Below docker-compose File

  • Create a Docker Network
 docker network create dev_network
Enter fullscreen mode Exit fullscreen mode
  • Replica Set Configuration Script

Create a file named replicaset.sh under the scripts directory to configure the replica set:

scripts/replicaset.sh

  • Grant Permissions to the Script Ensure the script has execute permissions so Docker can access it:
 chmod +x scripts/replicaset.sh
Enter fullscreen mode Exit fullscreen mode
  • Update the Host File for Resolvers

Map the Mongo paths to localhost by editing the /etc/hosts file:

127.0.0.1   primary secondary1 secondary2 # mongo docker resolvers
Enter fullscreen mode Exit fullscreen mode
  • Create the Docker Compose File

Define your MongoDB configuration in a docker-compose.yml file:

  • Run the Docker Compose File Start the containers using the following command:
docker-compose up
Enter fullscreen mode Exit fullscreen mode

🎉 That’s it! Your MongoDB primary and secondaries are up and running. The replica set is configured and ready to use.

Your MongoDB connection URL is:

mongodb://localhost:27020,localhost:27021,localhost:27022/dbname?replicaSet=rs0&retryWrites=true&w=majority

Top comments (0)