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

MongoDB Atlas与AWS EC2连接超时问题求助

无法从AWS EC2连接MongoDB Atlas M0集群:findOne操作超时

本人是AWS新手,尝试将MongoDB Atlas M0集群与运行Node.js/React栈的AWS EC2实例连接,但调用后端登录接口时出现如下错误:

Operation user_profile.findOne() buffering timed out after 10000ms

本地开发机和WSL2 Ubuntu CLI均可正常连接,已配置MongoDB白名单为所有IP,AWS安全组出站策略正确,入站开放27000-28018端口,但问题依旧。

连接MongoDB的代码

import config from './config';
import app from './app';
import { connect } from 'mongoose'; // MongoDB
import { ServerApiVersion } from 'mongodb';

import https from 'https';
import AWS from 'aws-sdk';

const makeLogger = (bucket: string) => {
    const s3 = new AWS.S3({
        accessKeyId: <ACCESS_KEY_ID>,
        secretAccessKey: <SECRET_ACCESS_KEY>
    });
    return (logData: any, filename: string) => {
        s3.upload({
            Bucket: bucket, // pass your bucket name
            Key: filename, // file will be saved as testBucket/contacts.csv
            Body: JSON.stringify(logData, null, 2)
        }, function (s3Err: any, data: any) {
            if (s3Err) throw s3Err
            console.log(`File uploaded successfully at ${data.Location}`)
        });
        console.log(`log (${filename}): ${logData}`);
    };
};
const log = makeLogger('xxx-xxxx');
log(config.MONGO_DB_ADDRESS, 'mongo_db_address.txt');

const credentials = <CREDENTIALS>

connect(config.MONGO_DB_ADDRESS, {
    sslKey: credentials,
    sslCert: credentials,
    serverApi: ServerApiVersion.v1
}) //, { useNewUrlParser: true })
.then(() => console.log('Connected to MongoDB'))
.catch((err) => console.error('Failed connection to MongoDB', err));

app.on('error', error => {
    console.error('app error: ' + error);
});

app.listen(config.WEB_PORT, () => {
    console.log(`Example app listening on port ${config.WEB_PORT}`);
});

出现超时的登录接口代码

router.post('/signin', async (req, res) => {

    var form_validation = signin_schema.validate({
        email: req.body.email,
        password: req.body.password,
    });

    if (form_validation.error) {
        console.log('form validation sent');
        //return res.status(400).send(form_validation);
        return res.status(400).send({
            kind: 'ERROR',
            message: 'Sorry - something didn\'t go well. Please try again.'
        });
    }

    var User = model('model', UserSchema, 'user_profile');

    User.findOne({ email: req.body.email }, (err: any, the_user: any) => {
        if (err) {
            return res.status(400).send({
                kind: 'ERROR',
                message: err.message
            });
        }

        if (!the_user) {
            return res.status(400).send({
                kind: 'ERROR',
                message: 'the_user undefined',
            });
        }

        compare(req.body.password, the_user.password)
            .then((result) => {

                if (result == true) {

                    const user_payload = { name: the_user.name, email: the_user.email };
                    const access_token = sign(user_payload, config.SECRET_TOKEN);

                    res.cookie('authorization', access_token, {
                        httpOnly: true,
                        secure: false,
                        maxAge: 3600000,
                    });

                    return res.send({ kind: "LOADING" });
                    // return res.send(access_token);

                } else {

                    return res.status(400).send({
                        kind: 'ERROR',
                        message: 'Sorry - wrong password or email used.'
                    });

                }

            })

    })
});

排查方向

  • 检查EC2实例网络连通性:在EC2实例上执行telnet <atlas-cluster-host> 27017或nc -zv <atlas-cluster-host> 27017,测试是否能连接到MongoDB Atlas的端口。同时确认VPC网络ACL的出站规则允许访问27017端口。
  • 简化SSL配置:MongoDB Atlas默认使用CA证书验证,不需要客户端证书。尝试移除连接配置中的sslKey和sslCert参数,使用默认SSL设置:
    connect(config.MONGO_DB_ADDRESS, {
        serverApi: ServerApiVersion.v1
    })
    
  • 验证连接状态:在登录接口中先检查Mongoose连接状态,避免未建立连接时执行查询:
    import mongoose from 'mongoose';
    
    // ...接口代码中添加
    if (mongoose.connection.readyState !== 1) {
        return res.status(500).send({
            kind: 'ERROR',
            message: 'MongoDB connection not established'
        });
    }
    
  • 检查DNS解析:在EC2实例上执行nslookup <atlas-cluster-host>,确认能正常解析集群域名。若解析失败,检查VPC是否启用了DNS解析和DNS主机名。
  • 查看Atlas连接日志:登录MongoDB Atlas控制台,查看集群的连接日志,确认是否有EC2实例IP的连接尝试及拒绝记录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:48:04