MongoDB: Allow Remote Access

Out of the box, MongoDB doesn’t allow remote connections, because by default it has no authentication enabled and is listening on localhost only.

If you try to connect to MongoDB without remote access being allowed, you will get this error:

Error: couldn’t connect to server $MongoDB:$Port, connection attempt failed:SocketException: Error connecting to $MongoDB:$Port :: caused by :: Connection refused … exception: connect failed

In this article i will show how to allow remote access to MongoDB.

Cool Tip: Enable authentication and authorization in MongoDB! Read More →

Allow Remote Access to MongoDB

By default, MongoDB is listening on 127.0.0.1:27017 only:

$ sudo netstat -tnlp
Proto Recv-Q Send-Q Local Address   Foreign Address State  PID/Program name
tcp        0      0 127.0.0.1:27017 0.0.0.0:*       LISTEN 1106/mongod

Open MongoDB configuration file /etc/mongod.conf and change bindIp by adding required LAN interfaces or configure it to bind to all interfaces, for example:

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,192.168.0.100 # Enter 0.0.0.0,:: to bind to all interfaces

Restart mongod to apply modifications:

$ sudo service mongod restart

Now mongod is listening on configured interfaces and can be accessible remotely:

$ sudo netstat -tnlp
Proto Recv-Q Send-Q Local Address       Foreign Address State  PID/Program name
tcp        0      0 127.0.0.1:27017     0.0.0.0:*       LISTEN 19757/mongod
tcp        0      0 192.168.0.100:27017 0.0.0.0:*       LISTEN 19757/mongod

Cool Tip: Connect to remote MongoDB server using mongo shell! Read More →

2 Replies to “MongoDB: Allow Remote Access”

  1. Some Random Dude says: Reply

    In v4.0.5 the config file is yaml so you need to wrap the list in square brackets:

    # network interfaces
    net:
    port: 27017
    bindIp: [0.0.0.0, ::]

  2. I get this error:
    Error: couldn’t connect to server **:27017, connection attempt failed: NetworkTimeout: Error connecting to **:27017 :: caused by :: Socket operation timed out :
    connect@src/mongo/shell/mongo.js:374:17

    How to fix it?

Leave a Reply