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

Azure Cosmos DB for MongoDB(vCore)连接超时问题求助

排查Azure Cosmos DB for MongoDB(vCore)连接超时问题

问题背景

我正在搭建Node.js连接Azure Cosmos DB for MongoDB(vCore)的应用,已复制实验室代码排除代码层面问题,执行npm start后出现MongoServerSelectionError: Server selection timed out after 30000 ms错误。

相关配置信息

.env文件配置

MONGODB_URI=mongodb+srv://<user>:<password>@phase-1-db.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000

其中<user>替换为Azure Cosmos DB for MongoDB(vCore)概览页的管理员用户名,<password>替换为对应管理员密码。

index.js连接代码

require('dotenv').config();
const { MongoClient } = require('mongodb');

async function main() { 
    // initialize the MongoDB client
    const client = new MongoClient(process.env.MONGODB_URI);
    
    // connects to the database service and outputs messages to the console to indicate the connection status.
    try {
        await client.connect();
        console.log('Connected to MongoDB');
      } catch (err) {
        console.error(err);
      } finally {
        await client.close();
        console.log('Disconnected from MongoDB');
      }
}

main().catch(console.error);

package.json配置

{  
  "name": "mongodb-nodejs-devguide-first-cosmos-db-application",  
  "version": "1.0.0",  
  "description": "A Node.js application that connects to MongoDB",  
  "main": "index.js",  
  "scripts": {  
    "start": "node index.js"  
  },  
  "dependencies": {  
    "mongodb": "6.3.0",
    "dotenv": "16.4.4"  
  },  
  "author": "Microsoft",  
  "license": "MIT"  
}  

错误日志

npm start

> mongodb-nodejs-devguide-first-cosmos-db-application@1.0.0 start
> node index.js

MongoServerSelectionError: Server selection timed out after 30000 ms
    at EventTarget.<anonymous> (/Users/user1/Desktop/github/Azure-OpenAI-Tutorials/first_cosmos_db_application/NodeJS/node_modules/mongodb/lib/sdam/topology.js:276:34)
    at [nodejs.internal.kHybridDispatch] (node:internal/event_target:822:20)
    at EventTarget.dispatchEvent (node:internal/event_target:757:26)
    at abortSignal (node:internal/abort_controller:374:10)
    at TimeoutController.abort (node:internal/abort_controller:396:5)
    at Timeout.<anonymous> (/Users/user1/Desktop/github/Azure-OpenAI-Tutorials/first_cosmos_db_application/NodeJS/node_modules/mongodb/lib/utils.js:1011:92)
    at listOnTimeout (node:internal/timers:573:17)
    at process.processTimers (node:internal/timers:514:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'c.phase-1-db.mongocluster.cosmos.azure.com:10260' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}
Disconnected from MongoDB

排查步骤

  • 检查网络访问权限
    确认运行Node.js应用的设备IP已添加到Azure Cosmos DB for MongoDB(vCore)的防火墙允许列表:

    1. 登录Azure门户,进入目标Cosmos DB资源
    2. 导航到网络 -> 防火墙和虚拟网络
    3. 确保当前设备公网IP已被添加,或临时开启"允许从所有网络访问"(仅测试环境使用,生产环境需严格限制)
  • 验证连接字符串正确性

    1. 从Azure Cosmos DB概览页复制官方提供的连接字符串,对比.env配置:
      • 确认用户名、密码无拼写错误,若密码含特殊字符需确保已正确转义
      • 检查端口号是否匹配(vCore默认端口为10260,日志中显示端口正确,但需确认资源配置未修改端口)
    2. 使用MongoDB Compass工具测试连接该字符串,排除应用外的连接问题
  • 检查TLS配置
    Azure Cosmos DB要求使用TLS 1.2及以上版本,确认Node.js环境支持:

    1. 执行以下命令检查Node.js默认TLS版本:
      node -e "console.log(process.defaultTlsVersion)"
      
    2. 若版本低于1.2,升级Node.js或在创建MongoClient时手动指定TLS版本:
      const client = new MongoClient(process.env.MONGODB_URI, {
        tls: true,
        tlsVersion: 'TLSv1.2'
      });
      
  • 调整连接超时参数
    尝试增加连接超时时间,修改MongoClient初始化代码:

    const client = new MongoClient(process.env.MONGODB_URI, {
      serverSelectionTimeoutMS: 60000 // 调整为60秒
    });
    
  • 检查资源状态
    登录Azure门户,确认目标Cosmos DB资源处于正常运行状态,无停机或性能告警

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 14:31:01