Cannot connect MongoDB Container to NodeJs App within compose file - node.js

here is my docker-compose.yml file:
version: "3.7"
services:
dev:
image: "node_rest_dev_img"
build:
context: .
container_name: node_rest_dev
working_dir: /usr/src/app
volumes:
- .:/usr/src/app
ports:
- 3010:3010
restart: always
depends_on:
- database_mongoDB
networks:
- node_rest_network
database_mongoDB:
image: mongo
container_name: node_rest_mongoDB
environment:
- MONGO_INITDB_ROOT_USERNAME=mongo_admin
- MONGO_INITDB_ROOT_PASSWORD=secret
ports:
- 27017:27017
volumes:
- ./__MONGO_DATA__:/data/db
networks:
- node_rest_network
networks:
node_rest_network:
driver: bridge
the problem is that i have a network called node_rest_network and those two containers suppose to talk to each other only within that network, here is my connection string in my express app
import mongoose from "mongoose";
import AppConfig from "./AppConfig";
const connect = (ops = {}) => {
return mongoose.connect(
"mongodb://mongo_admin:secret#database_mongoDB/rest_standard_api",
{
...ops,
useNewUrlParser: true,
useUnifiedTopology: true
}
);
};
export default connect;
but unfortunately when ever i ran docker-compose up this is not working, i always get this error in my terminal:
Cannot connect to Mongo DB MongooseError [MongooseServerSelectionError]: connect ECONNREFUSED 127.0.0.1:27017
node_rest_dev | at new MongooseServerSelectionError (/usr/src/app/node_modules/mongoose/lib/error/serverSelection.js:22:11)
node_rest_dev | at NativeConnection.Connection.openUri (/usr/src/app/node_modules/mongoose/lib/connection.js:823:32)
node_rest_dev | at Mongoose.connect (/usr/src/app/node_modules/mongoose/lib/index.js:333:15)
node_rest_dev | at connect (/usr/src/app/built/utils/mongoConnect.js:1:1064)
node_rest_dev | at /usr/src/app/built/app.js:8:373
node_rest_dev | at Object.<anonymous> (/usr/src/app/built/app.js:8:562)
node_rest_dev | at Module._compile (internal/modules/cjs/loader.js:1147:30)
node_rest_dev | at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
node_rest_dev | at Module.load (internal/modules/cjs/loader.js:996:32)
node_rest_dev | at Function.Module._load (internal/modules/cjs/loader.js:896:14)
node_rest_dev | at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
node_rest_dev | at internal/main/run_main_module.js:17:47 {
node_rest_dev | message: 'connect ECONNREFUSED 127.0.0.1:27017',
node_rest_dev | name: 'MongooseServerSelectionError',
node_rest_dev | reason: TopologyDescription {
node_rest_dev | type: 'Single',
node_rest_dev | setName: null,
node_rest_dev | maxSetVersion: null,
node_rest_dev | maxElectionId: null,
node_rest_dev | servers: Map(1) { 'localhost:27017' => [ServerDescription] },
node_rest_dev | stale: false,
node_rest_dev | compatible: true,
node_rest_dev | compatibilityError: null,
node_rest_dev | logicalSessionTimeoutMinutes: null,
node_rest_dev | heartbeatFrequencyMS: 10000,
node_rest_dev | localThresholdMS: 15,
node_rest_dev | commonWireVersion: null
node_rest_dev | },
node_rest_dev | [Symbol(mongoErrorContextSymbol)]: {}
node_rest_dev | }
can any one please hint me what am i doing wrong?

Related

MongooseServerSelectionError: getaddrinfo ENOTFOUND mongo

I just built a simple app with mongoDB and nodejs, and I used docker compose to do whole packing process for my app, but when I run docker-compose up my mongo service is fine, but my node app cant connect to my mongo and crash, I research many way to resolve that problems on google, but Unfortunately it isn't still working for my app,
Hope everyone can help me,
Thank you
ex info:
structure my project:
structure
Log error
connection error: MongooseServerSelectionError: getaddrinfo
ENOTFOUND mongo
node-app_1 | at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:825:32)
node-app_1 | at /app/node_modules/mongoose/lib/index.js:409:10
node-app_1 | at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:41:5
node-app_1 | at new Promise (<anonymous>)
node-app_1 | at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:40:10)
node-app_1 | at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1262:10)
node-app_1 | at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:408:20)
node-app_1 | at Object.<anonymous> (/app/app.js:9:10)
node-app_1 | at Module._compile (node:internal/modules/cjs/loader:1102:14)
node-app_1 | at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) {
node-app_1 | reason: TopologyDescription {
node-app_1 | type: 'Unknown',
node-app_1 | servers: Map(1) { 'mongo:27017' => [ServerDescription] },
node-app_1 | stale: false,
node-app_1 | compatible: true,
node-app_1 | heartbeatFrequencyMS: 10000,
node-app_1 | localThresholdMS: 15,
node-app_1 | setName: null,
node-app_1 | maxElectionId: null,
node-app_1 | maxSetVersion: null,
node-app_1 | commonWireVersion: 0,
node-app_1 | logicalSessionTimeoutMinutes: null
node-app_1 | },
node-app_1 | code: undefined
node-app_1 | }
node-app_1 | node:internal/process/promises:225
node-app_1 | triggerUncaughtException(err, true /* fromPromise */);
Connection String:
mongoose.connect('mongodb://mongo-db:27017/test', { useNewUrlParser: true });
Dockerfile-node:
FROM node:15.3.0
WORKDIR /app
COPY package\*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
Dockerfile-mongo:
FROM mongo:4.4
WORKDIR /data/db
VOLUME /data/db
EXPOSE 27017
CMD ["mongod"]
docker-compose.yml:
version: '3'
services:
node-app:
build:
context: .
dockerfile: Dockerfile-node
ports:
- 3000:3000
depends_on:
- mongo-db
networks:
- mongo-db
mongo-db:
build:
context: .
dockerfile: Dockerfile-mongo
ports:
- 27017:27017
volumes:
- mongo-data:/data/db
networks:
- mongo-db
volumes:
mongo-data:
networks:
mongo-db:
name: mongo-db
Update Answer
Dang, I realize my docker didn't rebuild when I type "docker-compose up" so it made up error 'ENOTFOUND mongo', so to resolve this problem you will remove that image in docker and type "docker-compose up" again,
It worked for me!

MongooseServerSelectionError every first time I start nodemon, always solved by rs command

Every first time I start my server via nodemon connected to my local MongoDB I get the following timeout error, which is solved by the rs command.
I would like to know why the error happens and why restarting the server resolves it.
Here's the complete log (database name and parts of paths omitted), and below it my node server's connection's js code:
$ nodemon index.js 3000
[nodemon] 2.0.16
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js 3000`
Listening on port 3000
Error connecting to "mongodb://127.0.0.1:27017/<databasename>":
MongooseServerSelectionError: connection timed out
at Connection.openUri (...\node_modules\mongoose\lib\connection.js:824:32)
at ...\node_modules\mongoose\lib\index.js:380:10
at ...\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (...\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (...\node_modules\mongoose\lib\index.js:1225:10)
at Mongoose.connect (...\node_modules\mongoose\lib\index.js:379:20)
at Object.<anonymous> (...\index.js:9:10)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10) {
reason: TopologyDescription {
type: 'Single',
servers: Map(1) { '127.0.0.1:27017' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined
}
...\node_modules\mongodb\lib\sdam\topology.js:293
const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);
^
MongoServerSelectionError: connection timed out
at Timeout._onTimeout (...\node_modules\mongodb\lib\sdam\topology.js:293:38)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7) {
reason: TopologyDescription {
type: 'Single',
servers: Map(1) {
'127.0.0.1:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: '127.0.0.1', port: 27017 },
address: '127.0.0.1:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 366612820,
lastWriteDate: 0,
error: MongoNetworkTimeoutError: connection timed out
at connectionFailureError (...\node_modules\mongodb\lib\cmap\connect.js:381:20)
at Socket.<anonymous> (...\node_modules\mongodb\lib\cmap\connect.js:302:22)
at Object.onceWrapper (node:events:627:28)
at Socket.emit (node:events:513:28)
at Socket._onTimeout (node:net:562:8)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7) {
[Symbol(errorLabels)]: Set(0) {}
}
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.12.0
[nodemon] app crashed - waiting for file changes before starting...
rs
[nodemon] starting `node index.js 3000`
Listening on port 3000
Connected to "mongodb://127.0.0.1:27017/<databasename>"
Node server's connection's js code:
const mongoose = require('mongoose');
const urlDBLocale = 'mongodb://127.0.0.1:27017/<databasename>?directConnection=true';
const urlCloudDB = process.env.dbUrl;
// in prod, change urlDBLocale to urlCloudDB
mongoose.connect(urlDBLocale, {useNewUrlParser: true, useUnifiedTopology: true})
.then(()=>{
console.log('Connected to "mongodb://127.0.0.1:27017/<databasename>"');
// or, if cloud, console.log('Connected to cloud-database');
})
.catch(error =>{
console.log('Error connecting to "mongodb://127.0.0.1:27017/<databasename>":');
console.log(error);
})

serverSelectionError when connect to localhost in mongoose?

Hi I tried every thing like mongoose.connect('mongodb://localhost/blog') but I am not able to connect mongoose to node here is my code....
const express = require('express')
const mongoose = require('mongoose')
const articleRouter = require('./routes/articles')
const app = express()
mongoose.connect('mongodb://localhost:27017/blog')
app.set('view engine','ejs')
Here is the error:
/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/connection.js:807
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at NativeConnection.Connection.openUri (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/connection.js:807:32)
at /home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/index.js:342:10
at /home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/index.js:1181:10)
at Mongoose.connect (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/index.js:341:20)
at Object.<anonymous> (/home/vishwajeet/webdeve/MARKDOWN-BLOG/server.js:8:10)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 774709,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
at connectionFailureError (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongodb/lib/cmap/connect.js:375:20)
at Socket.<anonymous> (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongodb/lib/cmap/connect.js:295:22)
at Object.onceWrapper (node:events:646:26)
at Socket.emit (node:events:526:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
[Symbol(errorLabels)]: Set(0) {}
}
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined
}
Hey I think your problem is that you don't have mongodb installed on your computer.
Once you download it you can change
mongoose.connect('mongodb://localhost:27017/blog')
to
mongoose.connect('mongodb://127.0.0.1/blog')
if the problem is still there
Youtube video for mongodb install

Local Mongoose Connection Timing Out And Crashing

I am working on setting up a very simple full stack web application that can handle users signing up and logging in. For this, I have employed mongoose as a local database to store my users information after signup. This was working for a long time, but I recently ran my app after a week away from it and this happened:
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at NativeConnection.Connection.openUri (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/connection.js:845:32)
at /Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/index.js:345:10
at /Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/index.js:1135:10)
at Mongoose.connect (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/index.js:344:20)
at Object.<anonymous> (/Users/hca/Desktop/fullstacksus/server.js:26:10)
at Module._compile (node:internal/modules/cjs/loader:1102:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
at Module.load (node:internal/modules/cjs/loader:967:32)
at Function.Module._load (node:internal/modules/cjs/loader:807:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47 {
reason: TopologyDescription {
type: 'Unknown',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
node:internal/process/promises:225
triggerUncaughtException(err, true /* fromPromise */);
^
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at NativeConnection.Connection.openUri (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/connection.js:845:32)
at /Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/index.js:345:10
at /Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/index.js:1135:10)
at Mongoose.connect (/Users/hca/Desktop/fullstacksus/node_modules/mongoose/lib/index.js:344:20)
at Object.<anonymous> (/Users/hca/Desktop/fullstacksus/server.js:26:10)
at Module._compile (node:internal/modules/cjs/loader:1102:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
at Module.load (node:internal/modules/cjs/loader:967:32)
at Function.Module._load (node:internal/modules/cjs/loader:807:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47 {
reason: TopologyDescription {
type: 'Unknown',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) {
'localhost:27017' => ServerDescription {
address: 'localhost:27017',
error: Error: connect ECONNREFUSED 127.0.0.1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1133:16) {
name: 'MongoNetworkError'
},
roundTripTime: -1,
lastUpdateTime: 57762916,
lastWriteDate: null,
opTime: null,
type: 'Unknown',
topologyVersion: undefined,
minWireVersion: 0,
maxWireVersion: 0,
hosts: [],
passives: [],
arbiters: [],
tags: []
}
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
[nodemon] app crashed - waiting for file changes before starting...
For reference, this is a very stripped down version of my server.js file:
if (process.env.NODE_ENV !== "production") {
require('dotenv').config({ path: '.env' });
}
const express = require('express');
const mongoose = require('mongoose');
const app = express();
mongoose.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, 'useCreateIndex': true });
mongoose.connection.on('error', error => console.log(error));
mongoose.connection.once('open', () => console.log("Connected To Database"));
const indexRouter = require('./routes/index');
app.use('/', indexRouter);
app.listen(3030);
and this is my .env file:
MONGO_URL=mongodb://localhost/fullstacksus
very simple, and, as of a week ago working perfectly.
I think you have to run the MongoDB server as well before starting the project.
you may use any of the following, (Supposedly, you already have installed the mongodb in your system).
I will suggest you to install the mongodb community edition from the following link
https://docs.mongodb.com/manual/administration/install-community/
Then after installing it.
Just start the service in a terminal by the command
Ubuntu
sudo systemctl start mongod
Windows
After setting the environment variable path to mongod.exe run the following command in the terminal.
mongod

Mongoose Server Selection Error ECONNREFUSED with a docker-compose

I'm trying to create a minimal dockerised Mongo Express React Node stack. Mongoose connects fine to my dockerised mongo when using node, but fails when trying inside docker.
back.js :
const express = require('express');
const app = express();
const mongoose = require('mongoose');
mongoose.connect('mongodb://mongo:27017/test', {useNewUrlParser: true, useUnifiedTopology: true},
() => {console.log("connection established")})
.catch(error => handleError(error));
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// some stuff
});
app.listen(3000, function () {
console.log('Express-js listening on port 3000')
});
});
docker-compose.yml :
version: "3.7"
services:
mongodb:
image: mongo:latest
container_name: mongo
volumes:
- mongodb-data:/data/db
ports:
- 27017:27017
express-js:
build: ./back-express/ #local Dockerfile
ports:
- 3000:3000
depends_on:
- mongodb
volumes:
mongodb-data:
Dockerfile :
FROM node:lts
WORKDIR ./
COPY package.json yarn.lock ./
RUN yarn install --production
COPY . .
CMD ["node", "back.js"]
Error :
express-js_1 | connection error: MongooseError [MongooseServerSelectionError]: connect ECONNREFUSED 127.0.0.1:27017
express-js_1 | at new MongooseServerSelectionError (/node_modules/mongoose/lib/error/serverSelection.js:22:11)
(...)
express-js_1 | message: 'connect ECONNREFUSED 127.0.0.1:27017',
express-js_1 | name: 'MongooseServerSelectionError',
express-js_1 | reason: TopologyDescription {
express-js_1 | type: 'Single',
express-js_1 | setName: null,
express-js_1 | maxSetVersion: null,
express-js_1 | maxElectionId: null,
express-js_1 | servers: Map { 'localhost:27017' => [ServerDescription] },
express-js_1 | stale: false,
express-js_1 | compatible: true,
express-js_1 | compatibilityError: null,
express-js_1 | logicalSessionTimeoutMinutes: null,
express-js_1 | heartbeatFrequencyMS: 10000,
express-js_1 | localThresholdMS: 15,
express-js_1 | commonWireVersion: null
express-js_1 | },
express-js_1 | [Symbol(mongoErrorContextSymbol)]: {}
express-js_1 | }
I tried to add this before the last line in my Dockerfile :
CMD ["sleep", "10"]
but it had no effect.
I have no idea what's going wrong. I've spent a long time searching the Internet. Any help would make my day.
Full code accessible here : https://github.com/npasquie/back-express
clone this project inside the first : https://github.com/npasquie/back-express
A friend of mine find the answer. The code works but I forgot to rebuild my images with docker-compose build before launching the containers.
Sorry for the original question not being really useful, still I think I won't delete it because it may help other beginners who made the same mistake.

Resources