How to Construct a MongoDB Sharded Cluster Connection String for External Clients
External clients connect to the sharded cluster by targeting the two mongos router instances exposed on host ports 27117 and 27118, using a connection string format like mongodb://127.0.0.1:27117,127.0.0.1:27118.
When deploying a MongoDB sharded cluster using Docker Compose, external applications cannot connect directly to the internal shard nodes. Instead, they must route requests through the mongos query routers. In the minhhungit/mongodb-cluster-docker-compose repository, the Docker Compose configuration exposes two router containers on specific host ports, making it straightforward to construct a MongoDB sharded cluster connection string for external access.
Understanding the Router Architecture
The cluster deploys two mongos instances named router01 and router02. According to the docker-compose.yml file, each router maps container port 27017 to distinct host ports:
- router01 (container
router-01): Host port 27117 - router02 (container
router-02): Host port 27118
These mappings are defined in the router services section of the compose file. External clients treat these host ports as the entry points to the entire sharded cluster.
Basic Connection String Format
For unauthenticated connections, the standard MongoDB connection string lists both router endpoints separated by commas:
mongodb://<host>:27117,<host>:27118
Replace <host> with the IP address or hostname where Docker is running. For local development, this is typically 127.0.0.1 or localhost. The repository's README explicitly documents this example:
mongodb://127.0.0.1:27117,127.0.0.1:27118
Listing both routers enables driver-level load balancing and automatic failover. If router01 becomes unavailable, the driver seamlessly routes requests to router02 without application code changes.
Connecting with Authentication
The repository includes a with-keyfile-auth variant that enables internal authentication between cluster nodes. When using this configuration, external clients must provide credentials in the connection string.
The format becomes:
mongodb://<username>:<password>@<host>:27117,<host>:27118/?authSource=admin
Key parameters:
- username/password: Credentials for a user created in the
admindatabase - authSource=admin: Required because authentication credentials are stored in the admin database, not the default test database
Note that the repository does not automatically create client users. You must connect to a router via mongosh or the shell and execute db.createUser() in the admin database before external authenticated connections will succeed.
Practical Connection Examples
MongoDB Shell (mongosh)
Connect to the cluster using the MongoDB shell:
mongosh "mongodb://127.0.0.1:27117,127.0.0.1:27118"
With authentication:
mongosh "mongodb://myUser:myPass@127.0.0.1:27117,127.0.0.1:27118/?authSource=admin"
Node.js
Using the native MongoDB driver:
const { MongoClient } = require('mongodb');
const uri = 'mongodb://127.0.0.1:27117,127.0.0.1:27118';
const client = new MongoClient(uri, { useUnifiedTopology: true });
async function run() {
await client.connect();
const db = client.db('MyDatabase');
const coll = db.collection('MyCollection');
await coll.insertOne({ msg: 'Hello from Node.js' });
console.log('Document inserted');
await client.close();
}
run().catch(console.error);
Python (PyMongo)
from pymongo import MongoClient
uri = "mongodb://127.0.0.1:27117,127.0.0.1:27118"
client = MongoClient(uri)
db = client["MyDatabase"]
coll = db["MyCollection"]
coll.insert_one({"msg": "Hello from Python"})
print("Inserted document")
client.close()
C# (.NET)
The repository includes sample .NET clients in client/DemoMongoClusterWriter/Program.cs and client/DemoMongoClusterReader/Program.cs. Basic connection:
using MongoDB.Driver;
var connectionString = "mongodb://127.0.0.1:27117,127.0.0.1:27118";
var client = new MongoClient(connectionString);
var database = client.GetDatabase("MyDatabase");
var collection = database.GetCollection<BsonDocument>("MyCollection");
await collection.InsertOneAsync(new BsonDocument { { "msg", "Hello from .NET!" } });
Summary
- External clients connect exclusively through the mongos routers exposed on host ports 27117 and 27118.
- The standard MongoDB sharded cluster connection string format lists both router endpoints:
mongodb://host:27117,host:27118. - Listing multiple routers provides automatic failover and load balancing at the driver level.
- When using the
with-keyfile-authconfiguration, append credentials andauthSource=adminto the connection string. - The repository provides working examples in Node.js, Python, C#, and MongoDB Shell.
Frequently Asked Questions
Do I need to include the shard replica set names in the connection string?
No. External clients should never connect directly to shard replica sets in a MongoDB sharded cluster. Always connect through the mongos routers. The connection string only needs to list the router endpoints (ports 27117 and 27118). The mongos process handles routing queries to the appropriate shards internally.
Can I connect to just one router instead of listing both?
Yes, a connection string with a single router (e.g., mongodb://127.0.0.1:27117) will work. However, listing both routers in the connection string is strongly recommended for high availability. If the single router you specified goes down, your application loses connectivity. With both routers listed, MongoDB drivers automatically fail over to the healthy instance.
How do I enable authentication for external clients?
The repository ships with a with-keyfile-auth folder containing a Docker Compose configuration that enables internal authentication. To enable client authentication:
- Start the cluster using the keyfile-auth configuration.
- Connect to one of the routers using the shell.
- Create a user in the
admindatabase:db.createUser({user: "myUser", pwd: "myPass", roles: [{role: "readWrite", db: "myDatabase"}]}). - Update your connection string to include the credentials and
authSource=adminparameter.
What host IP should I use when connecting from outside the Docker host?
Use the IP address or hostname of the machine running Docker. If you are connecting from a different machine on the network, replace 127.0.0.1 with the Docker host's network IP address (e.g., 192.168.1.100). Ensure that the host ports (27117 and 27118) are not blocked by firewalls and are accessible from the client machine.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →