Error connecting web server on Elastic Beanstalk with database server on MongoDB Atlas - node.js

I am trying to connect my web servers on Elastic Beanstalk with my database servers on MongoDB Atlas, but somehow I get the following error
Listening at http://:::3001
Unable to connect to the mongodb instance. Error: { MongoNetworkError: failed to connect to server [<server>.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to <server>.mongodb.net:27017 closed]
at Pool.<anonymous> (/var/app/current/node_modules/mongodb-core/lib/topologies/server.js:431:11)
at Pool.emit (events.js:198:13)
at connect (/var/app/current/node_modules/mongodb-core/lib/connection/pool.js:557:14)
at callback (/var/app/current/node_modules/mongodb-core/lib/connection/connect.js:109:5)
at runCommand (/var/app/current/node_modules/mongodb-core/lib/connection/connect.js:129:7)
at Connection.errorHandler (/var/app/current/node_modules/mongodb-core/lib/connection/connect.js:321:5)
at Object.onceWrapper (events.js:286:20)
at Connection.emit (events.js:198:13)
at TLSSocket.<anonymous> (/var/app/current/node_modules/mongodb-core/lib/connection/connection.js:350:12)
at Object.onceWrapper (events.js:286:20)
at TLSSocket.emit (events.js:198:13)
at _handle.close (net.js:606:12)
at TCP.done (_tls_wrap.js:388:7)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
Listening at http://:::3001
(node:11482) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
Listening at http://:::3001
I am using mongoose as follows
mongoose.connect('mongodb+srv://<UserName>:<Password>#<cluster>.mongodb.net/test?retryWrites=true&w=majority',
{ useNewUrlParser: true, useUnifiedTopology: true })
.catch(function (reason) {
console.log('Unable to connect to the mongodb instance. Error: ', reason);
});
The problem is not in the IP Whitelist on MongoDB Atlas, since I already ssh'd into the server on elastic beanstalk and from there connected to the Mongo Servers on Atlas directly. The problem is in the code, although I can't seem to see it.

I had the same issue. Add 0.0.0.0/0 to your IP whitelist.

Related

MongoNetworkError on first connect using Docker and NodeJS

I'm still incredibly new to coding. I'm trying to launch an app using docker, everything goes well until I get this error:
{ MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (/app/node_modules/mongodb/lib/core/topologies/server.js:433:11)
at Pool.emit (events.js:198:13)
at createConnection (/app/node_modules/mongodb/lib/core/connection/pool.js:577:14)
at connect (/app/node_modules/mongodb/lib/core/connection/pool.js:1007:11)
at makeConnection (/app/node_modules/mongodb/lib/core/connection/connect.js:31:7)
at callback (/app/node_modules/mongodb/lib/core/connection/connect.js:247:5)
at Socket.err (/app/node_modules/mongodb/lib/core/connection/connect.js:276:7)
at Object.onceWrapper (events.js:286:20)
at Socket.emit (events.js:198:13)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
name: 'MongoNetworkError',
[Symbol(mongoErrorContextSymbol)]: {} }
[nodemon] clean exit - waiting for changes before restart
I have mongodb running as a server on Windows 10, and I also have it running in another window, so I'm not sure what could be causing it. I've tried all solutions on this page, but to no avail. Thanks in advance!
Localhost is the container, not your machine. When working with containers, you need to think of container as a separate machine and use a full network adressess to communicate between your machine and container.
I was using a similar concept like yours. Try to run both node-app and Mongo service under the same network.
In Mongo connection string, the Hostname should be the same as your service name mentioned in docker-compose.yml file.

How to connect to a MongoDB running on an aws ec2 host (linux) out of docker

Situation:
I prototyped a small web (node.js) app and dockerized it for deployment and replicability purposes.
The app speaks with a MongoDB running directly on the host.
Problem:
On the server (AWS EC2 instance, only Port 80 and 443 open), I am not able to interact with MongoDB and I am wondering why.
docker run --net="host" -e 'NODE_ENV=production' -e 'MONGO_URI=mongodb://USER:PASSWORD!#172.31.32.1:27017/test_db' DOCKER_IMAGE
MongoDB connected ...
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
HTTP Server started on port 80
(node:1) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [172.31.32.1:27017] on first connect [MongoNetworkError: connection timed out
at connectionFailureError (/app/server/node_modules/mongodb/lib/core/connection/connect.js:377:14)
at Socket.<anonymous> (/app/server/node_modules/mongodb/lib/core/connection/connect.js:287:16)
at Object.onceWrapper (events.js:284:20)
at Socket.emit (events.js:196:13)
at Socket._onTimeout (net.js:432:8)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7) {
name: 'MongoNetworkError',
[Symbol(mongoErrorContextSymbol)]: {}
}]
at Pool.<anonymous> (/app/server/node_modules/mongodb/lib/core/topologies/server.js:433:11)
at Pool.emit (events.js:196:13)
at /app/server/node_modules/mongodb/lib/core/connection/pool.js:571:14
at /app/server/node_modules/mongodb/lib/core/connection/pool.js:994:11
at /app/server/node_modules/mongodb/lib/core/connection/connect.js:40:11
at callback (/app/server/node_modules/mongodb/lib/core/connection/connect.js:262:5)
at Socket.<anonymous> (/app/server/node_modules/mongodb/lib/core/connection/connect.js:287:7)
at Object.onceWrapper (events.js:284:20)
at Socket.emit (events.js:196:13)
at Socket._onTimeout (net.js:432:8)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7) {
name: 'MongoNetworkError',
[Symbol(mongoErrorContextSymbol)]: {}
}
I initially tried localhost instead of the IP address, but that does not work. It throws an authentication error (which is somewhat strange). Since there is no host.docker.internal for Linux I had to (temporarily) resolve to the explicit IP address. The IP address that I am using I got via:
netstat -nr | grep '^0\.0\.0\.0' | awk '{print $2}'
What I find very strange is that I am not getting an Authentication error but a Timeout error, so to me it seems like the app is able to connect to Mongo. Also, the "MonogDB connected ..." would indicate that, as it is produced by the following line in my server script.
mongoose
.connect(DB, { useNewUrlParser: true })
.then(console.log("MongoDB connected ..."))
.catch(err => console.log(err));
For completeness sake, the same setup (i.e. dockerized app and running MongoDB directly on the host) worked without a problem locally.
Also, I am able to enter the Mongo Shell on the server via mongo.
Any explanation or tip is appreciated!
If mongo DB is running outside of the Docker, you can use the private IP of the EC2 instance to connect with Mongo DB (running on Host) from inside Docker.
EC2_PRIVATE_IP=$(curl http://169.254.169.254/latest/meta-data/local-ipv4)
docker run --net="host" -e 'NODE_ENV=production' -e 'MONGO_URI=mongodb://USER:PASSWORD!#$EC_PRIVATE_IP:27017/test_db' DOCKER_IMAGE

MongoNetworkError : failed to connect to server

First time working with mongoDb inside a Node.js app (using mLab) but i'm unable to connect.
Same exact code works just fine if i try to connect to mongoDB Atlas.
// not working with mLab link and credentials
mongoose.connect(mLabConnectionString)
.then(success => console.log(success))
.catch(error => console.log(error))
// working with atlas link and credentials
mongoose.connect(atlasConnectionString)
.then(success => console.log(success))
.catch(error => console.log(error))
Followed these steps https://docs.mlab.com/troubleshooting-connection-issues/
and i do have network access, i'm using database user credentials to connect (not my mLab account credentials) and my password just contains chars and numbers. That's the error i'm getting :
{ MongoNetworkError: failed to connect to server [***my_database***]
on first connect [MongoNetworkError: getaddrinfo ENOTFOUND ***my_database*** ***my_database***]
at Pool.<anonymous> (C:\Users\akain\Desktop\devconnector\node_modules\mongodb-core\lib\topologies\server.js:564:11)
at Pool.emit (events.js:182:13)
at Connection.<anonymous> (C:\Users\akain\Desktop\mongotest\node_modules\mongodb-core\lib\connection\pool.js:317:12)
at Object.onceWrapper (events.js:273:13)
at Connection.emit (events.js:182:13)
at Socket.<anonymous> (C:\Users\akain\Desktop\mongotest\node_modules\mongodb-core\lib\connection\connection.js:246:50)
at Object.onceWrapper (events.js:273:13)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
Now the weird part : If i try to connect to mLab using mongo shell, not only everything works (from the shell), but i'm also able to connect without problem from my app. As soon as i close the shell and restart the app i get the error again.
I've also tried using mongoDb Node client instead of mongoose getting the same exact behaviour.

MongoDB refuses Connection on Windows 10 machine

i'm running a Node.js app on my Windows 10 machine. I have Mongoose installed and setup like this:
// Init Database
var mongoose = require("mongoose");
var mongoDB = "mongodb://127.0.0.1/sampledata"
mongoose.connect(mongoDB);
var db = mongoose.connection;
// Check DB connection
db.once("open", function(){
console.log("Connected to MongoDB");
});
// Check for DB errors
db.on("error", function(err){
console.log(err);
});
Now, when I start the server with nodemon, the following error appears in the console:
{ MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (C:\Users\...\node_modules\mongodb-core\lib\topologies\server.js:564:11)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (C:\Users\...\node_modules\mongodb-core\lib\connection\pool.js:317:12)
at Connection.g (events.js:291:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket.<anonymous> (C:\...\node_modules\mongodb-core\lib\connection\connection.js:246:50)
at Socket.g (events.js:291:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1278:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ]
}
When I try to start mongo over the console, I get the following error:
C:\Program Files\MongoDB\Server\4.0\bin>mongo
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:27017
2018-10-03T19:05:24.194+0200 E QUERY [js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte (in english: A connection couldn't be established, because the target computer has refused the connection). :
connect#src/mongo/shell/mongo.js:257:13
#(connect):1:6
exception: connect failed
I've never encountered this error before and as stupid as it sounds, yesterday everything worked fine. Haven't changed the code or anything, so it must be an issue with my computer I guess.
Do you guys know what could cause this error?
TL;DR
Start mongod server
mongod
Open another terminal window
Start mongo shell
mongo
Longer Version:
Open Command prompt as an administrator and run netstat -anb, check which port mongodb is listening to (Usually 27017). If you dont see a listing for mongo then it means that mongod is not running, so go ahead and start mongod.exe from the mongodb binaries(or if environment variables are set, run mongod from anywhere on your cmd).
if this doesnt work, your firewall is probably blocking access on that port, so check that out
I was getting this error as well. In my case, I was trying to upgrade to MongoDB 4.0 without first upgrading to 3.6.
Please see https://docs.mongodb.com/manual/release-notes/4.0/#upgrade-procedures if you recently updated MongoDB.

mongoose wont connect to ec2 mongodb instance

i'm trying to create a node.js server that connect to my mongodb hosted on ec2 instance. I'm doing like this :
mongoose.connect("mongodb://username:password#ec2-xx-xx-xxx-xxx.eu-central-1.compute.amazonaws.com:27017/dbname");
db.on('error', err => {
console.log('Mongoose default connection error:', err);
db.close();
});
db.once('open', () => {
console.log(`Mongoose default connection open`);
});
But it keep saying me this error :
Mongoose default connection error: { MongoError: failed to connect to server [xxx] on first
connect [MongoError: connect ETIMEDOUT xxx:27017]
at Pool.<anonymous> (/Users/jmisiti/hm-landing/node_modules/mongodb-core/lib/topologies/server.js:336:35)
at emitOne (events.js:115:13)
at Pool.emit (events.js:210:7)
at Connection.<anonymous> (/Users/jmisiti/hm-landing/node_modules/mongodb-core/lib/connection/pool.js:280:12)
at Object.onceWrapper (events.js:318:30)
at emitTwo (events.js:125:13)
at Connection.emit (events.js:213:7)
at Socket.<anonymous> (/Users/jmisiti/hm-landing/node_modules/mongodb-core/lib/connection/connection.js:189:49)
at Object.onceWrapper (events.js:316:30)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at emitErrorNT (internal/streams/destroy.js:62:8)
at _combinedTickCallback (internal/process/next_tick.js:102:11)
at process._tickCallback (internal/process/next_tick.js:161:9)
name: 'MongoError',
message: 'failed to connect to server [xxx] on first connect [MongoError: connect ETIMEDO
UT xxx:27017]' }
My connection string is 100% sure it works. My mongoose version work great with my mongodb version. Any idea ? :)
PS : Ports are open on 27017 and there's already one of my aws instance using my mongodb. So i'm sure it work.
Make sure that you have registered 27017 port in Outbound ports In the EC2 security group.
Then try to access the DB. and if you have already added port and still experiencing the error then check if you MongoDB process is running as a service(i.e. in the background). If not then follow this procedure
Got it. I can't connect from my localhost to my mongodb server (Don't know why) but when i'm connecting to my mongodb server from my ec2 instance it work. So it's fine :)

Resources