skip to Main Content

I am trying to connect my Heroku App, written in node.js, to a cluster hosted at Atlas MongoDB Cloud.

When running my api locally in my machine I can access the database with no problem using my current IP Address. I’m also able to connect to the cluster using mongo shell.

However, when running the App in Heroku, the connection cannot be established. In the Browser JS console,In heroku, I get the error:

MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/

I also try using some add-ons on Heroku like Fixie and Fixie Socks to get an Ip Address, still giving me the same Error.

My question is what do i need to do to establish the secure connection between Heroku and MongoDB Atlas?

2

Answers


  1. you can add 0.0.0.0/0 ip address. it worked for me !
    because this is setting to mongoDB Atlas that you allow ip address from any client or you can get your heroku ipaddress by follow this link
    https://devcenter.heroku.com/articles/private-spaces

    Login or Signup to reply.
  2. If you want a set of static IPs from which to connect to MongoDB Atlas, your options are to either use Heroku Private Spaces or an addon which provides a SOCKS5 proxy for outbound connections. As of this writing, the two addons in the Heroku Elements marketplace that do this are Fixie Socks and QuotaGuard Static.

    Whichever addon you choose, you can connect through their SOCKS5 proxy by providing an options object to mongoose.connect:

    const mongoose = require('mongoose');
    const fixieData = process.env.FIXIE_SOCKS_HOST.split(new RegExp('[/(:\/@/]+'));
    
    mongoose.connect(process.env.DB_CONNECTION,
        {
          proxyUsername: fixieData[0],
          proxyPassword: fixieData[1],
          proxyHost: fixieData[2],
          proxyPort: fixieData[3]
         },
        (error) => {
          if(error){
            console.log(error);
          } else {
            console.log('Connected to database');
          }
        }
    );
    

    Both addons also offer binaries which allow you to connect from libraries that don’t natively support SOCKS5 proxies (fixie-wrench and QGTunnel), but these should be unnecessary for your use case.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search