Unable to connect the mongodb container to node container in docker - mongodb

I made 3 docker containers from 2 images in this repo and 1 using MongoDB public image. I turned ON all three containers using sudo docker-compose -f docker-compose.yaml up
docker-compose.yaml is:
version: '3'
services:
frontend:
image: samar080301/mern-frontend:1.0
ports:
- 3000:3000
backend:
image: samar080301/mern-backend:1.0
ports:
- 5000:5000
mongodb:
image: mongo:latest
ports:
- 27017:27017
But the MongoDB couldn't connect with the node server and gave this error:
backend_1 | > crud-app#1.0.0 start /home/app
backend_1 | > node server.js
backend_1 |
backend_1 | (node:18) 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.
backend_1 | (Use `node --trace-deprecation ...` to show where the warning was created)
backend_1 | App running on port 5000
backend_1 | Error with the database! MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017
backend_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
backend_1 | name: 'MongoNetworkError'
backend_1 | }]
backend_1 | at Pool.<anonymous> (/home/app/node_modules/mongodb/lib/core/topologies/server.js:438:11)
backend_1 | at Pool.emit (events.js:315:20)
backend_1 | at /home/app/node_modules/mongodb/lib/core/connection/pool.js:562:14
backend_1 | at /home/app/node_modules/mongodb/lib/core/connection/pool.js:995:11
backend_1 | at /home/app/node_modules/mongodb/lib/core/connection/connect.js:32:7
backend_1 | at callback (/home/app/node_modules/mongodb/lib/core/connection/connect.js:280:5)
backend_1 | at Socket.<anonymous> (/home/app/node_modules/mongodb/lib/core/connection/connect.js:310:7)
backend_1 | at Object.onceWrapper (events.js:422:26)
backend_1 | at Socket.emit (events.js:315:20)
backend_1 | at emitErrorNT (internal/streams/destroy.js:84:8)
backend_1 | at processTicksAndRejections (internal/process/task_queues.js:84:21)
backend_1 | (node:18) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017
backend_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
backend_1 | name: 'MongoNetworkError'
backend_1 | }]
Code of backend/db.js:
const mongoose = require('mongoose');
// Allow Promises
mongoose.Promise = global.Promise;
// Connection
mongoose.connect('mongodb://localhost:27017/db_test', { useNewUrlParser: true });
// Validation
mongoose.connection
.once('open', () => console.log('Connected to the database!'))
.on('error', err => console.log('Error with the database!', err));
Terminal Output of docker inspect mongodb:
Terminal output after adding the mongo uri as environment variable:
backend_1 | App running on port 5000
backend_1 | (node:19) UnhandledPromiseRejectionWarning: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
backend_1 | (node:19) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
New error:
backend_1 | Error with the database! MongoNetworkError: failed to connect to server [merncrudapp_mongodb_1:27017] on first connect [Error: connect ECONNREFUSED 172.23.0.3:27017
backend_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
backend_1 | name: 'MongoNetworkError'
backend_1 | }]

Try to connect not using localhost but a container name. So for example, if you want to connect to MongoDB from another container (in the same docker network) you can use mongodb:27017.
It should work.

When you run docker-compose up, the following happens:
A network called MernCrudApp(takes the default name of the directory) is created.
A container is created using the frontend's configuration. It joins the network MernCrudApp under the name frontend.
A container is created using the backend's configuration. It joins the network MernCrudApp under the name backend.
A container is created using mongodb’s configuration. It joins the network MernCrudApp under the name mongodb.
now if you use mongodb://localhost:27017/db_test to connect to the db, the node app will look for MongoDB in the backend container which you will get a connection error since it does not exist.
To remedy this, change the MongoDB connection string to mongodb://mongodb:27017/db_test so that it
Aditional comments
I would recommend the following to help solve some problems you might face in the future using the current configuration.
Add the connection string as an environment variable. This will make it easier for you to change the DB instances without rebuilding the container.
Since the backend application depends on the database add depend_on on the docker-compose files so that the MongoDB container starts before the backend container

Modify your backend/db.js code.
Your are getting error because when you mention 'localhost' in code your container is trying to connect to backend container on port 2017 which not in use.
// Connection
//mongodb is a container name of mongo image
mongoose.connect('mongodb://mongodb:27017/db_test', { useNewUrlParser: true });
Pro Tip -
1)If you are in same docker network then use hostname or Docker Container Name to communicate/Link with each other.
2)Never use container IP address in code if IP's are not assign manually. Whenever you restart container it may change.

Related

mongo-express does not connect to mongodb

i have installed mongodb and i am able to connect via shell, now i am trying to install mongo-express, the installation was successful, i copied config.default.js file in config.js but it can't connect to mongo. As can be seen from the error it cannot retrieve the hostname
(node:3085) 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.
(Use `node --trace-deprecation ...` to show where the warning was created)
Could not connect to database at index "0"
(node:3085) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [undefined:27017] on first connect [Error: getaddrinfo ENOTFOUND undefined
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:67:26) {
name: 'MongoNetworkError'
}]
at Pool.<anonymous> (/Users/name/.config/yarn/global/node_modules/mongodb/lib/core/topologies/server.js:438:11)
at Pool.emit (events.js:315:20)
at /Users/name/.config/yarn/global/node_modules/mongodb/lib/core/connection/pool.js:562:14
at /Users/name/.config/yarn/global/node_modules/mongodb/lib/core/connection/pool.js:995:11
at /Users/name/.config/yarn/global/node_modules/mongodb/lib/core/connection/connect.js:32:7
at callback (/Users/name/.config/yarn/global/node_modules/mongodb/lib/core/connection/connect.js:280:5)
at Socket.<anonymous> (/Users/name/.config/yarn/global/node_modules/mongodb/lib/core/connection/connect.js:310:7)
at Object.onceWrapper (events.js:422:26)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
(node:3085) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:3085) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I had the same error.
Forcing the connection URL fixed it for me :
mongo-express --url "mongodb://localhost:27017" --admin
(--admin option allows to list all databases)

Error at connecting to MongoDB Atlas via VPC Peering from GCP Kubernetes Cluster

I am connecting a Nodejs app running on the GCP Kubernetes cluster. Before, it worked fine, when I enabled VPC Peering and I was using the connection string (Private). It is recommended on the Atlas dashboard:
mongodb+srv://(username):(password)#<cluster_name>-pri.m6tkv.gcp.mongodb.net/<database_name>?retryWrites=true&w=majority
I followed this tutorial to setup: https://docs.atlas.mongodb.com/security-vpc-peering/
I cannot understand since my app has been running for quite a while with this configuration. But one fine day, the app running on a pod in my GCP cluster is unable to connect.
Thats the error message:
Connected mongodb failed MongoNetworkError: failed to connect to server [<cluster_name>-00-00-pri.m6tkv.gcp.mongodb.net:27017] on first connect [MongoNetworkError: connection timed out
at connectionFailureError (/app/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js:406:14)
at TLSSocket.<anonymous> (/app/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js:294:16)
at Object.onceWrapper (events.js:299:28)
at TLSSocket.emit (events.js:210:5)
at TLSSocket.Socket._onTimeout (net.js:469:8)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7) {name: 'MongoNetworkError' }] at Pool.<anonymous> (/app/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/server.js:438:11)
at Pool.emit (events.js:210:5)
at /app/node_modules/mongoose/node_modules/mongodb/lib/core/connection/pool.js:562:14
at /app/node_modules/mongoose/node_modules/mongodb/lib/core/connection/pool.js:1009:9
at /app/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js:31:7
at callback (/app/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js:264:5)
at TLSSocket.<anonymous> (/app/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js:294:7)
at Object.onceWrapper (events.js:299:28)
at TLSSocket.emit (events.js:210:5)
at TLSSocket.Socket._onTimeout (net.js:469:8)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7)
I switched back to the old connection (Standard), my app works again. The connection string:
mongodb+srv://(username):(password)#<cluster_name>.m6tkv.gcp.mongodb.net/<database_name>?retryWrites=true&w=majority
So connection via VPC Peering is having some problem, I couldn't find any clue.

Can't connect to mongodb cloud

I'm working on a web application with node.js and using Mongodb for database. everything is cool when I run my app in localhost. but when I run it in a shared host it gives an error which looks like its Mongoose connection problem.
here is my code:
const uri = 'mongodb://****:****#iranroboticacademy-bdziw.mongodb.net/test';
mongoose.connect(uri,{ useNewUrlParser: true });
mongoose.connection.once('open', function(){
console.log('DataBase is connected. ');
}).on('error', function(error){
console.log('Connection error:', error);
});
and here is the erro that I get when I run the app in host:
Connection error: { MongoNetworkError: failed to connect to server [iranroboticacademy-shard-00-00-bdziw.mongodb.net:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 3.226.212.92:27017]
at Pool.<anonymous> (/home/iranrob1/public_html/node_modules/mongodb/lib/core/topologies/server.js:433:11)
at Pool.emit (events.js:182:13)
at createConnection (/home/iranrob1/public_html/node_modules/mongodb/lib/core/connection/pool.js:577:14)
at connect (/home/iranrob1/public_html/node_modules/mongodb/lib/core/connection/pool.js:1021:9)
at makeConnection (/home/iranrob1/public_html/node_modules/mongodb/lib/core/connection/connect.js:31:7)
at callback (/home/iranrob1/public_html/node_modules/mongodb/lib/core/connection/connect.js:247:5)
at TLSSocket.err (/home/iranrob1/public_html/node_modules/mongodb/lib/core/connection/connect.js:276:7)
at Object.onceWrapper (events.js:273:13)
at TLSSocket.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',
[Symbol(mongoErrorContextSymbol)]: {} }
(node:6409) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [iranroboticacademy-shard-00-00-bdziw.mongodb.net:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 3.226.212.92:27017]
at Pool.<anonymous> (/home/iranrob1/public_html/node_modules/mongodb/lib/core/topologies/server.js:433:11)
at Pool.emit (events.js:182:13)
at createConnection (/home/iranrob1/public_html/node_modules/mongodb/lib/core/connection/pool.js:577:14)
at connect (/home/iranrob1/public_html/node_modules/mongodb/lib/core/connection/pool.js:1021:9)
at makeConnection (/home/iranrob1/public_html/node_modules/mongodb/lib/core/connection/connect.js:31:7)
at callback (/home/iranrob1/public_html/node_modules/mongodb/lib/core/connection/connect.js:247:5)
at TLSSocket.err (/home/iranrob1/public_html/node_modules/mongodb/lib/core/connection/connect.js:276:7)
at Object.onceWrapper (events.js:273:13)
at TLSSocket.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)
(node:6409) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:6409) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Sure you can use the free tier of MongoDB Cloud.
It’s actually much easier to mantain than the hosted version as you have visually all under control, automatic backups etc.
https://mongodb.com
I have asked my host provider in a ticket and they said it doesn’t support mongodb. I have written everything with mongodb database in my application and I really can’t change it into other things. I need to use it in this host. Is there anyone who has a solution for this?!
try to use 'connect to your aplication', copy the then change the

Can not connect MongoDB docker-compose

Can not connect mongodb run in docker-compose
MONGO_URL=mongodb://db:27017/500ae_cms
error:
MongoDB connection error: mongodb://db:27017/500ae_cms.
MongoNetworkError: failed to connect to server [db:27017] on first connect [Error: getaddrinfo ENOTFOUND db
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26) {
name: 'MongoNetworkError',
errorLabels: [Array],
}]
docker-compose file
For your db service you expose port 27775 but in your app you try to connect to 27017.
Docker resolves the service name in an IP address but this fails here (too?)
failed to connect to server [db:27017];;; getaddrinfo ENOTFOUND db
should at least be something like:
failed to connect to server [db:27017] on first connect [Error: connect ECONNREFUSED 17.19.0.2:27017
Can you try running nslookup db from the api container? If that resolves, then it might be an issue with your mongo driver.

How to connect to external Mongo (MLab) from a Node app in Docker

I have a database setup on Mlab and I have aconnection string that does work remotely. If I run my node app on docker using my local mongo, everything works as expected, however if I change the configuration and connect to my Mlab mongo, I get the following error:
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/topologies/server.js:564:11)
at emitOne (events.js:116:13)
at Pool.emit (events.js:211:7)
at Connection.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/connection/pool.js:317:12)
at Object.onceWrapper (events.js:317:30)
at emitTwo (events.js:126:13)
at Connection.emit (events.js:214:7)
at Socket.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/connection/connection.js:246:50)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:66:8)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickDomainCallback (internal/process/next_tick.js:219:9)
(node:24) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6)
Apart from handling the error on Node side (which I'm not catching, but that's another problem), how can I connect to an external mongo server form my Docker container?
I've seen this and follow the steps described there but it didn't help me.
Any suggestions?
EDIT
This is a Node app. In my Dockerfile I have the following setting:
ENV DB_HOST=mongodb+srv://<user>:<password>#<mlab>/<db_name>?retryWrites=true
And in my Node app where I have setup the database I have this:
mongoose.connect(process.env.DB_HOST, {useNewUrlParser: true, useFindAndModify: false, useCreateIndex: true});
When I print the above env variable at run time, I get the correct string for the db (running locally everything works fine).
I don't understand why the error shows localhost. This is my first time using Docker. Do I need any additional configuration so my container can talk to an external service?