【问题标题】:How to connect via mongoose and a ssh tunnel如何通过猫鼬和 ssh 隧道连接
【发布时间】:2016-07-02 01:58:46
【问题描述】:

我已经按如下方式设置了我的 mongod.conf,所以它只允许本地主机连接。

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

net:
  port: 27017
  bindIp: 127.0.0.1

然后我希望我的站点通过 ssh 连接到 mongodb,因此端口必须转换为 localhost。

但是如何将它与猫鼬的连接功能集成?

mongoose.connect(configDB.url, function(err){
  if (err){
    console.log('Error connecting to mongodb: ' + err)
  }
});

我找到了以下命令,但我不确定这是否是我需要的:

ssh -L 4321:localhost:27017 -i ~/.ssh/ssh_key user@ip-adress

这应该通过端口 4321 将我 ssh 到 localhost 对吗?所以我想我在nodejs mongoose的connect函数中需要这样的东西。我已尝试在 mongodb 安全教程中阅读此内容,但我根本无法将他们的说明链接到 nodejs。谁有这方面的经验?

【问题讨论】:

    标签: node.js mongodb ssh mongoose


    【解决方案1】:

    你快到了。建立独立于节点的隧道:

    ssh -Nf -p [db_server_ssh_port] [mongo_user]@[mongo_domain] -L \
    [local_db_port]:localhost:[remote_db_port]
    

    然后在节点内,使用 [local_db_port] 连接到 mongo:

    mongoose.connect(
      "mongodb://localhost:[local_db_port]/[db_name]",
      {"pass":"[db_pwd]"}
    )
    

    发送到 Web 服务器上的 [local_db_port] 的所有流量都将通过隧道发送到 [mongo_domain] 上的端口 [remote_db_port]。以下帖子提供了更多信息。是连接MySQL数据库,原理是一样的。

    Connect to MySQL using SSH Tunneling in node-mysql

    【讨论】:

      【解决方案2】:

      建立独立于节点的隧道:

      ssh -L [your given port]:localhost:27017 [username of ssh]@[ip address of ssh matchine] -f -N
      

      之后,您已经为 mongo 数据库包含了给定的端口。 在nodejs中,你必须像这样设置猫鼬连接

      'mongodb://localhost:[your given port number]/[database name]'
      

      好好享受吧

      【讨论】:

      • 太棒了!很好的答案!
      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2021-02-15
      • 2018-10-06
      • 2016-02-04
      • 2021-11-13
      • 2012-06-19
      • 2019-05-13
      相关资源
      最近更新 更多