This guide explains how to set up a MongoDB sharding cluster using Docker Compose and how to use it in a Node.js application.
- Docker
- Docker Compose
- Node.js
Run the following command to start the MongoDB containers:
docker-compose up -d
You can customize the Docker Compose file to suit your needs. For example, you can change the memory limits, CPU limits, and volume paths.
volumes:
- F:/Database/MongoDBCluster/configs1:/data/db
volumes:
- /mnt/f/Database/MongoDBCluster/configs1:/data/db
First, make the script executable:
chmod +x initiate-cluster.sh
Then, run the script:
./initiate-cluster.sh
Run the batch script:
initiate-cluster.bat
This script will set up the config server replica set, the shard replica set, and add the shard to the cluster.
To connect to the MongoDB sharding cluster from a Node.js application, use the following connection string:
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:30000";
const client = new MongoClient(uri);
try {
await client.connect();
console.log("Connected to MongoDB sharding cluster");
// ... your application code ...
} finally {
await client.close();
}
}
main().catch(console.error);
Replace // ... your application code ...
with your actual application logic.
To stop the MongoDB containers, run:
docker-compose down
This will stop and remove the containers.
Credit to Iman Far (imanfar.com)