将Heroku App连接到Atlas MongoDB Cloud服务

为了解决这个问题:是否需要在Heroku上获得SSL支持才能使用SSLbuild立HerokuAtlas MongoDB Cloud之间的连接? (TSL / SSL连接是访问Atlas MongoDB云服务的要求 )。

我正在尝试将使用node.js编写的Heroku应用程序连接到Atlas MongoDB Cloud托pipe的集群。

我当前的数据库是在mLab(作为Heroku插件)托pipe的,用于通过mongoose访问集群的MongoDB URI是(使用xxx来省略保密信息):

MONGODB_URI="mongodb://xxx:xxx@xxx-a0.mlab.com:23266,xxx-a1.mlab.com:xxx/xxx?replicaSet=rs-xxx" 

现在我已经将数据从mLab迁移到Atlas MongoDB Cloud,我正在使用URI访问集群:

 MONGODB_URI="mongodb://xxx:xxx@cluster0-shard-xxx.mongodb.net:xxx,cluster0-shard-xxx.mongodb.net:xxx,cluster0-shard-xxx.mongodb.net:xxx/xxx?replicaSet=xxx&ssl=true&authSource=admin" 

当我的机器在本地运行我的Heroku应用程序时,我可以访问数据库没有问题。 我也可以使用mongo shell连接到群集。

但是,在Heroku中运行App时,无法build立连接。 在浏览器JS控制台,我得到503服务不可用消息。 在heroku中,我得到错误:

 no primary found in replica set 

我知道Atlas MongoDB Cloud需要SSL连接,与mLab不同。 在我的本地机器上,我想使用自签名证书来成功连接到群集。

我的问题是:我是否需要在Heroku中获得SSL支持才能访问build立Heroku和MongoDB Atlas之间的安全连接? 或者Heroku中的SSL suport只需要客户端/ Heroku安全连接?

我认为可能会解决您的问题

免责声明:我既没有使用Heroku也没有使用MongoDB Atlas,但我正在研究它们。

根据我发现的Github问题[1],如果您没有将MongoDB Atlas中的服务器IP地址列入白名单,您将收到错误消息。

阅读MongoDB Atlas文档[2],我看到与Heroku dynos结合使用的唯一方法是将0.0.0.0/0 (即所有地址)添加到您的MongoDB Atlas白名单。

试一试,然后报告是否可以实例化一个连接。

在SSL上

试图回复SSL问题,我不认为你需要在Heroku上启用它,虽然我不完全确定。

如果MongoDB服务器执行了证书validation,则连接到它的Node.js代码必须如下所示(来自Node.js驱动程序文档[3]):

 var MongoClient = require('mongodb').MongoClient, f = require('util').format, fs = require('fs'); // Read the certificates var ca = [fs.readFileSync(__dirname + "/ssl/ca.pem")]; var cert = fs.readFileSync(__dirname + "/ssl/client.pem"); var key = fs.readFileSync(__dirname + "/ssl/client.pem"); // Connect validating the returned certificates from the server MongoClient.connect("mongodb://localhost:27017/test?ssl=true", { server: { sslValidate:true , sslCA:ca , sslKey:key , sslCert:cert , sslPass:'10gen' } }, function(err, db) { db.close(); }); 

如果MongoDB服务器不检查任何SSL证书,则可以简单地使用如下所示的代码(也取自Node.js驱动程序文档[3]):

 var MongoClient = require('mongodb').MongoClient; MongoClient.connect("mongodb://localhost:27017/test?ssl=true", function(err, db) { db.close(); }); 

鉴于Atlas文档[4]包含以下用于从Node.js连接到它的示例代码,我认为您不必在Heroku上启用SSL:

 var MongoClient = require('mongodb').MongoClient; var uri = "mongodb://kay:myRealPassword@mycluster0-shard-00-00-wpeiv.mongodb.net:27017,mycluster0-shard-00-01-wpeiv.mongodb.net:27017,mycluster0-shard-00-02-wpeiv.mongodb.net:27017/admin?ssl=true&replicaSet=Mycluster0-shard-0&authSource=admin"; MongoClient.connect(uri, function(err, db) { db.close(); }); 

 [1] https://github.com/meteor/meteor/issues/7492#issuecomment-236562860 [2] https://docs.atlas.mongodb.com/security-whitelist/ [3] https://mongodb.github.io/node-mongodb-native/2.2/tutorials/connect/ssl/ [4] https://docs.atlas.mongodb.com/driver-connection/#node-js-driver-example