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
- 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
- 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
- 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
🎉 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)