You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将本地Node.js应用连接至DigitalOcean VPS上的MongoDB

本地Node.js应用连接DigitalOcean VPS上MongoDB的配置方案

必做检查与配置(已修改bindIp,仍需完成以下步骤)

  • 确认bindIp配置生效:确保MongoDB配置文件中的bindIp设置为0.0.0.0(允许所有IP访问,不推荐生产环境)或你的本地公网IP。修改后重启MongoDB服务:
    sudo systemctl restart mongod
    
  • 配置DigitalOcean防火墙:在VPS的防火墙规则中,添加入站规则,开放27017端口,仅允许你的本地公网IP访问,避免暴露给全网。
  • 验证MongoDB用户权限:登录MongoDB shell,确认所用用户拥有animal数据库的访问权限:
    use admin
    db.auth('admin_user', 'admin_pass')
    use animal
    // 查看用户权限
    db.getUser('your_username')
    // 若权限不足,执行授权
    db.grantRolesToUser('your_username', [{ role: 'readWrite', db: 'animal' }])
    
  • Node.js连接代码示例:确保代码正确使用连接URI,并处理连接异常:
    若使用Mongoose:
    const mongoose = require('mongoose');
    const mongoUri = 'mongodb://username:password@digital_ocean_server_ip:27017/animal';
    
    mongoose.connect(mongoUri, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    })
    .then(() => console.log('MongoDB连接成功'))
    .catch(err => console.error('连接失败:', err));
    
    若使用原生MongoDB驱动:
    const { MongoClient } = require('mongodb');
    const client = new MongoClient('mongodb://username:password@digital_ocean_server_ip:27017/animal');
    
    async function connectDB() {
      try {
        await client.connect();
        console.log('连接成功');
        const db = client.db('animal');
        // 后续业务操作
      } catch (err) {
        console.error('连接失败:', err);
      } finally {
        await client.close();
      }
    }
    connectDB();
    
  • 测试网络连通性:在本地终端用以下命令测试端口是否可达:
    nc -zv digital_ocean_server_ip 27017
    # 或使用telnet
    telnet digital_ocean_server_ip 27017
    
    若连接失败,排查VPS防火墙、本地网络出站限制或MongoDB服务状态。

常见问题排查

  • Authentication failed:检查用户名密码是否正确,以及该用户是否被授权访问animal数据库。
  • Connection refused:确认MongoDB服务正常运行(sudo systemctl status mongod)、bindIp配置正确、防火墙端口已开放。
  • Timeout error:检查VPS网络是否正常,本地网络是否能访问DigitalOcean服务器,可尝试ping服务器IP确认连通性。

内容的提问来源于stack exchange,提问作者aishvarya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 16:25:23