无法连接到MongoDB远程服务器

时间:2017-11-14 20:00:40

标签: mongodb ubuntu remote-server gcp

我在Google云计算实例上设置了mongodb,并尝试远程连接它。我的mongod.conf文件如下所示:

# mongod.conf
# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:
# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0
#processManagement:
security:
  authorization: 'enabled'

我在我的Google云端控制台中设置了一个防火墙规则,用于标记实例,并为IP范围tcp:27017打开0.0.0.0/0

检查端口27017,看起来mongo正在侦听:

sudo netstat -tulpn | grep 27017
tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN      3781/mongod 

总的来说,端口27017似乎也是开放的:

netstat --listen
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 *:27017                 *:*                     LISTEN   
...  

在实例上,我使用admin用户设置管理数据库:

>use admin
>db.createUser(
  {
    user: 'admin',
    pwd: 'somepass',
    roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
  }
)

我还为测试数据库设置了一个用户:

>use test
>db.createUser(
  {
    user: 'tester',
    pwd: 'apassword',
    roles: [{ role: "readWrite", db: "test" },
            { role: "read", db: "reporting" }]
  }
)

此用户在本地工作:

>use test
>db.auth('tester', 'apassword')
1

然而,当我尝试远程连接时,它失败了:

$ mongo -u tester -p apassword 12.345.67.890/test
MongoDB shell version v3.4.1
connecting to: mongodb://12.345.67.890/test
2017-11-14T12:47:07.369-0700 W NETWORK  [main] Failed to connect to 12.345.67.890:27017 after 5000ms milliseconds, giving up.
2017-11-14T12:47:07.370-0700 E QUERY    [main] Error: couldn't connect to server 12.345.67.890:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:234:13
@(connect):1:6
exception: connect failed

我不是网络专家,所以我现在已经非常疲惫不堪,不知道如何继续。

我错过了mongod.conf中的内容吗?我是否错误地设置了防火墙?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

我想出了一个解决方案,但我不清楚它为什么有效,而不是我原来的做法。

我的实例启用了http / https。这使用防火墙规则default-allow-httpdefault-allow-https。这些规则允许从任何地方(0.0.0.0/0)到tcp端口80和443的连接。我编辑了http规则并添加了tcp端口27017。

现在我可以连接到服务器了。

作为测试,我重置了http规则,并添加了另一个应用于所有打开tcp:27017到0.0.0.0/0的实例的规则。基本上所有内容都与名称和目标标签的http规则保存相同。有了这个改变,我无法连接到服务器。

看起来很奇怪,它并不像预期的行为,除非我对防火墙的理解不完整。

最后看起来要么设置mongo以使用其中一个http / https端口,要么将端口27017添加到这些规则中就可以了。

相关问题