【问题标题】:Can not connect to remote database无法连接到远程数据库
【发布时间】:2019-10-16 22:54:29
【问题描述】:

本地配置: Node.js 12.2.0

服务器配置: 虚拟主机 Ubuntu 18.04 MongoDB 3.2.22

有连接远程 mongodb 数据库的基本脚本。这将返回错误 - Cannot read property 'db' of null.

admintest 数据库。 对于管理员数据库,我创建了一个用户

db.createUser(
  {
    user: "root",
    pwd: "passw0rd",
    roles: [ { role: "root", db: "admin" } ]
  }
)

节点 app.js

// app.js

const MongoClient = require("mongodb").MongoClient;

// const url = "mongodb://root:passw0rd@46.173.213.195:27017/admin";
const url = "mongodb://46.173.213.195:27017/test";
const mongoClient = new MongoClient(url, { useNewUrlParser: true });

mongoClient.connect(function(err, client){      
    const db = client.db("admin");
    const collection = db.collection("users");
    let user = {name: "Tomy", age: 23};
    collection.insertOne(user, function(err, result){        
        if(err){ 
            return console.log(err);
        }
        console.log(result.ops);
        client.close();
    });
});
// package.json

{
   "name": "mongoapp",
   "version": "1.0.0",
   "dependencies": {
      "express": "^4.16.0",
      "body-parser": "^1.18.0",
      "mongodb": "^3.1.0"
   }
}

两个网址都返回错误。

我尝试了什么:

  1. 将 bindIp 更改为 any
///nano etc/mongod.conf

# network interfaces
net:
  port: 27017
#  bindIp: 127.0.0.1
  bindIp: 0.0.0.0

  1. sudo netstat -ntlp | grep 听
tcp    0    0 0.0.0.0:27017      0.0.0.0:*    LISTEN      17184/mongod
...
...
  1. 将此代码应用于 iptables
iptables -A INPUT -s 185.228.232.150 -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -d 185.228.232.150 -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT
  1. sudo systemctl status mongodb 表示 db 运行良好

谁能帮忙? 可以在您的计算机上测试代码。

更新: 根据那个帖子https://www.mkyong.com/mongodb/mongodb-bind-failed-errno99-cannot-assign-requested-address-for-socket/bindIp 不应该等于服务器IP。

【问题讨论】:

  • 你能通过命令行连接吗?
  • 我不打算使用 mongo shell 来处理数据库。还不能使用命令行。
  • 我在这里找到了解决方案 - stackoverflow.com/questions/49716190/… 剩下的问题是为什么 mongo 拒绝开始使用这个 IP

标签: node.js mongodb ubuntu-18.04


【解决方案1】:

您的数据库运行良好,应用程序也运行良好。问题出在数据库网络通信的应用程序中。请检查以下几点(假设您的数据库在 46.173.213.195 上运行)

  1. 数据库主机:检查是否在远程数据库主机中正确定义了必要的入站规则。这意味着数据库主机允许来自应用程序 IP 等的端口 27017。
  2. 数据库主机:将绑定 ip 更改为 46.173.213.195
  3. 应用主机:Telnet 46.173.213.195:27017。

现在,如果您的 telnet 成功,应用程序也应该能够与远程数据库通信。

【讨论】:

  • 1.你的意思是 mongod.conf 吗?我在上面显示了配置。 2. 感谢您的建议。奇怪的是,当我为 Bind ip 指向 46.173.213.195 时 - 我无法启动我的数据库工作。 Yaml 配置文件没有类型错误。
  • 另一个通知 - 防火墙处于非活动状态
  • (1)。入站规则适用于机器/主机而不是 DB (2)。如果您绑定了除 localhost 以外的任何 IP,则需要在启动 mongo 时添加 --host={your_bind_ip} 切换
  • 为什么要指向主机?这个 uri 已经有我的 IP 地址:const url = "mongodb://46.173.213.195:27017/test"
【解决方案2】:

我不知道是怎么回事 - 它刚刚开始工作。 绑定IP:0.0.0.0

我认为,经过大量重新加载和配置更新

【讨论】:

    猜你喜欢
    • 2013-12-14
    • 2017-08-20
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多