How to remotely connect to my MongoDB in my server with java?

我的未来我决定 提交于 2019-12-24 07:46:37

问题


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<Document> 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?


回答1:


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: <your-ip>, 127.0.0.1
...


来源:https://stackoverflow.com/questions/46041607/how-to-remotely-connect-to-my-mongodb-in-my-server-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!