2017-09-04 40 views
1

我想從我的筆記本電腦上的Java應用程序在我的服務器上使用我的MongoDB。 這是我的UFW設置如何用java遠程連接到我的服務器中的MongoDB?

[email protected]:~$ 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) 

起初,我只用了這樣的規則:

27017      ALLOW  1.234.56.78 

哪裏1.234.56.78是我的IP地址,但它沒有工作,所以我加了這條規則:

27017      ALLOW  Anywhere 

但這也沒有幫助。

這裏是我的Java代碼:

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()) + "}")); 

,但我得到:

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}}] 

最後一行的代碼(早就發現...

那麼如何我能解決這個問題嗎?

+0

https://docs.mongodb.com/manual/tutorial/configure-linux-iptables -firewall/ – Marged

+1

您是否在MongoDB配置文件中檢查了* bind_ip *設置?它應該允許外部連接(例如:0.0.0.0) - > https://docs.mongodb.com/v2.2/reference/configuration-options/#bind_ip –

回答

0

來自MongoDB documentation,它聲明在某些安裝中默認只偵聽本地連接(127.0.0.1)。

要遠程連接,你需要在/etc/mongod.conf配置公共入店接口:

... 
net: 
    port: 27017 
    bindIp: <your-ip>, 127.0.0.1 
... 
+0

綁定到該特定的IP不會將其打開到客戶端,是嗎? '0.0.0.0'可能是首選 –

+0

沒有工作。順便說一句!你可以請編輯你的答案,以便我的真實IP沒有顯示?@GonzaloMatheu –

+0

0.0.0.0也沒有工作@ cricket_007 –