Good morning, I deployed a MongoDB ReplicaSet cluster (3 nodes, 1 primary, 2 secondary) on Kubernetes using the following guide to do it:
Deploy it was successfully and I can connect by mongo shell to my remote MongoDB Cluster by user/pass, (each node of my MongoDB cluster has a PublicIP to connect it). I have created a DB and I have inserted data into it to check Replication and it works fine.
The problem comes when I try to connect to MongoDB cluster with a Java Application. Java code:
MongoCredential credential =
MongoCredential.createCredential("user",
"dbs","password".toCharArray());
Builder mongoBuilder = MongoClientOptions.builder();
MongoClientOptions options = mongoBuilder.build();
return new MongoClient(Arrays.asList(new ServerAddress("ip1",27017),
new ServerAddress("ip2", 27017),
new ServerAddress("ip3", 27017)),credential, options);
This solutions throws an Java connection error as follows:
[ERROR] - Exception thrown in MongoDBManagement.mongoDBManagement: Timed out after 30000 ms while waiting for a server that matches com.mongodb.client.internal.MongoClientDelegate$1@102a1baf. Client view of cluster state is {type=REPLICA_SET, servers=[{address=mongod-1.mongodb-service.default.svc.cluster.local:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: mongod-1.mongodb-service.default.svc.cluster.local}, caused by {java.net.UnknownHostException: mongod-1.mongodb-service.default.svc.cluster.local}}, {address=mongod-2.mongodb-service.default.svc.cluster.local:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: mongod-2.mongodb-service.default.svc.cluster.local}, caused by {java.net.UnknownHostException: mongod-2.mongodb-service.default.svc.cluster.local}}, {address=mongod-0.mongodb-service.default.svc.cluster.local:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: mongod-0.mongodb-service.default.svc.cluster.local}, caused by {java.net.UnknownHostException: mongod-0.mongodb-service.default.svc.cluster.local}}]; nested exception is com.mongodb.MongoTimeoutException:
Solved
I have found the problem, when you deploy a repSet, you must launch this command:
rs.initiate({_id: "MainRepSet", version: 1, members: [
{ _id: 0, host : "ip1:27017" },
{ _id: 1, host : "ip2:27017" }
{ _id: 2, host : "ip3:27017" }
]})
And I launched this command with the following hostanmes:
mongod-0.mongodb-service.default.svc.cluster.local;
mongod-1.mongodb-service.default.svc.cluster.local;
mongod-2.mongodb-service.default.svc.cluster.local
When I changed this by my publicIPs works fine.
Thanks