java ssh连接mongodb,如何使用Java远程连接到服务器中的MongoDB?

博主在尝试从Java应用远程访问MongoDB服务器时遇到连接拒绝的问题。已配置ufw防火墙允许27017端口访问,但仍然无法连接。MongoDB文档指出,默认情况下可能仅监听本地连接。解决方法是修改/etc/mongod.conf文件,添加公共可访问的接口。
摘要由CSDN通过智能技术生成

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

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值