且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

mongoDB,连接被拒绝

更新时间:2023-02-19 08:02:25

默认情况下,MongoDB仅绑定到回送接口,这使其只能从本地主机访问.要更改此内容,您需要在mongod.conf文件中编辑此行;

# /etc/mongod.conf

# Listen to local interface only. Comment out to listen on all interfaces.
bind_ip = 127.0.0.1

您可以将其更改为bind_ip = 127.0.0.1,192.168.1.102以允许LAN和本地连接,也可以删除或注释掉该行以允许所有连接.

有关更多信息: MongoDB –允许远程访问 >

Show my code

conf.set( "mongo.input.uri" , "mongodb://127.0.0.1/***.mrtest" );
conf.set( "mongo.output.uri" , "mongodb://127.0.0.1/***.mrtest_out2" );

the code runs without error when the host is localhost or 127.0.0.1. But when the host changed to my ip wlan0 192.168.1.102, it returned the following error

Cluster created with settings {hosts=[192.168.1.102:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Exception in monitor thread while connecting to server 192.168.1.102:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
    at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
    ... 3 more

I have open the port 27017.

sudo iptables -A INPUT -ptcp --dport 27017 -j ACCEPT

My OS is Ubuntu 14.04.

How should I fix it? Thank you!

By default MongoDB only binds to the loopback interface which makes it only accessible from localhost. To change that you need to edit this line in mongod.conf file;

# /etc/mongod.conf

# Listen to local interface only. Comment out to listen on all interfaces.
bind_ip = 127.0.0.1

you can change it to bind_ip = 127.0.0.1,192.168.1.102 to allow LAN and local connections or you can remove or comment out that line to allow all connections.

For more info : MongoDB – Allow remote access