I want to use my MongoDB on my server from a java application on my laptop.
this is my ufw setting
aran@Aran:~$ sudo ufw status
Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
22 ALLOW Anywhere
80 ALLOW Anywhere
443 ALLOW Anywhere
21/tcp ALLOW Anywhere
27017 ALLOW 1.234.56.78
27017 ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
22 (v6) ALLOW Anywhere (v6)
80 (v6) ALLOW Anywhere (v6)
443 (v6) ALLOW Anywhere (v6)
21/tcp (v6) ALLOW Anywhere (v6)
27017 (v6) ALLOW Anywhere (v6)
At first I only had this rule:
27017 ALLOW 1.234.56.78
Where 1.234.56.78 is my Ip address but it didn't work so I added this rule:
27017 ALLOW Anywhere
But That didn't help either.
Here is my java code:
java.util.logging.Logger.getLogger("org.mongodb.driver").setLevel(Level.OFF);
MongoClientURI connectionString = new MongoClientURI("mongodb://123.45.67.89:27017");
MongoClient mongoClient = new MongoClient(connectionString);
MongoDatabase CaptionBotUsers = mongoClient.getDatabase("CaptionBotUsers");
//CaptionBotUsers.createCollection("users", new CreateCollectionOptions().autoIndex(true));
MongoCollection users = CaptionBotUsers.getCollection("users");
long found = users.count(Document.parse("{_id : " + Long.toString(user.getId()) + "}"));
But I get:
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=123.45.67.89:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
For the Last line of the code(long found...)
So how can I fix this?
解决方案
From MongoDB documentation, it states that in some installations by default in only listens local connections (127.0.0.1).
To connect remotely you need to configure a public accesible interface in /etc/mongod.conf:
...
net:
port: 27017
bindIp: , 127.0.0.1
...