【问题标题】:MongooseServerSelectionError: connect ECONNREFUSEDMongooseServerSelectionError:连接 ECONNREFUSED
【发布时间】:2020-10-27 15:24:37
【问题描述】:

我正在尝试连接我的远程 EC2 mongodb,但它显示 MongooseServerSelectionError: connect ECONNREFUSED awsip:27017

在 aws mongodb 配置文件中,我将 bindIp 更改为 0.0.0.0,但我没有更改安全部分。

这是一个快速应用程序,我尝试通过两种方式与 aws mongodb 连接,两种方式都出现同样的错误,这是我的数据库设置:

Setup: 01

const DATABASE_URL = `mongodb://${cfg.dbUser}:${cfg.dbPass}@${cfg.dbHost}:${cfg.dbPort}/${cfg.dbName}`

server.listen(port, () => {
  mongoose.connect(DATABASE_URL,
    {
      // auth: {
      //   user: cfg.dbUser,
      //   password: cfg.dbPass
      // },
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then(() => {
      console.log("[ ???? ] AWS MongoDB database connected.");
      console.log(`[ Server ] waiting on: ${cfg.serverHost}:${port}`);
    })
    .catch(err => {
      console.log(
        "[ ???? ] Database connection error",
        { Error: err }
      );
    })
});


Setup: 02

const DATABASE_URL = `mongodb://${cfg.dbHost}:${cfg.dbPort}/${cfg.dbName}`
server.listen(port, () => {
  mongoose.connect(DATABASE_URL,
    {
      auth: {
        user: cfg.dbUser,
        password: cfg.dbPass
      },
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then(() => {
      console.log("[ ???? ] AWS MongoDB database connected.");
      console.log(`[ Server ] waiting on: ${cfg.serverHost}:${port}`);
    })
    .catch(err => {
      console.log(
        "[ ???? ] Database connection error",
        { Error: err }
      );
    })
});

我已经在 aws 中创建了数据库以及所有数据库用户权限凭证。

我正在使用 dotenv 加载所有 aws 凭据

当我尝试从我的机​​器连接 MongoDB-Compass 时也出现同样的问题。

connect ECONNREFUSED awsip:27017

这是我的终端图片

希望专家能帮助我。

【问题讨论】:

  • 您是否允许对 mongodb 安全组进行入站安全访问?
  • 是的,我有。对不起,我忘了提。
  • 两个服务器的安全组是什么样子的?
  • 好的,我可以和你分享我的安全组。自定义 TCP TCP 27017 0.0.0.0/0 - 自定义 TCP TCP 27017 ::/0 -
  • 在涉及您的应用程序之前获取与mongo shell 的连接。

标签: node.js mongodb amazon-web-services amazon-ec2


【解决方案1】:

解决方案是 ssh 端口转发。

首先确保您可以 ssh 进入您的 mongo 实例服务器并访问您的主要和次要副本节点

然后在具有公共 IPv4 地址的 mongo 服务器上使用这些设置为您的安全组创建一个新的入站规则

  1. 自定义 TCP 8000 0.0.0.0/0
  2. 自定义 TCP 8000 ::/0

对于端口转发部分

SSH 端口转发(SSH 隧道)在您当前机器上的端口与另一台服务器上的端口之间建立连接

这是一个例子

ssh -i aws-ssh-key.pem -g -N -f -L 8000:127.0.0.1:27017 ec2-user@10.0.8.10

当您启动此命令时,它的作用是打开并将当前机器 8000 的本地端口连接到您的 mongo 服务器:端口 127.0.0.1:27017,用户名和地址为 ec2-user@10.0.8.10

对于标志-g、-N、-f、-L

-g 允许远程主机连接到本地转发端口。

-N 不要执行远程命令。防止 ssh 在服务器上打开 shell

-f 在后台运行 ssh。

-L 指定要使用的本地端口

运行此命令列出进程

ps aux | grep ssh

运行此命令随时终止进程

kill -9 <pid>

我希望这能回答您的问题以获取更多参考

https://linux.die.net/man/1/ssh

https://www.youtube.com/watch?v=JKrO5WABdoY

https://jasonwatmore.com/post/2020/02/05/connect-to-remote-mongodb-on-aws-ec2-simply-and-securely-via-ssh-tunnel

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 2021-04-15
    • 1970-01-01
    • 2021-09-01
    • 2020-06-10
    • 2023-02-17
    • 2021-11-22
    • 2016-08-19
    • 1970-01-01
    相关资源
    最近更新 更多