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!
Related
I'm getting an error when my server is connecting to the MongoDB database. Both the server and mongoDB are in containers
The docker-compose files are as follows:
docker-compose.yml
version: '3'
services:
client:
build:
context: ./client
dockerfile: Dockerfile
ports:
- 3001:3001
networks:
- mern-network
volumes:
- ./client/src:/usr/app/src
- ./client/public:/usr/app/public
depends_on:
- server
environment:
- REACT_APP_SERVER=http://localhost:5001
# - CHOKIDAR_USEPOLLING=true
# container 1: backend node server
server:
build:
context: ./server
dockerfile: Dockerfile
ports:
- '5001:5001'
networks:
- mern-network
environment:
- PORT=5001
depends_on:
- mongo
# container 2: database
mongo:
image: mongo:4.4.13
networks:
- mern-network
environment:
- MONGO_INITDB_ROOT_USERNAME=docker_mongo
- MONGO_INITDB_ROOT_PASSWORD=password
volumes:
- mongo-db:/data/db
networks:
mern-network:
driver: bridge
volumes:
mongo-db:
docker-compose.dev.yml
version: '3'
services:
# container 3: client, dev settings
client:
command: npm start
# container 1: server, dev setting
server:
build:
args:
BUILD_ENV: development
volumes:
- ./server/:/app
# - ./server/app/node_modules
environment:
- BUILD_ENV=development
- MONGO_USER=docker_mongo
- MONGO_PASSWORD=password
- SESSION_SECRET=secret123456890qwerty
command: npm run dev
# container 2: database, dev settings
mongo:
environment:
- MONGO_INITDB_ROOT_USERNAME=docker_mongo
- MONGO_INITDB_ROOT_PASSWORD=password
I have no problems accessing into the mongodb database when I inspect the container using docker exec -it but error when I connect with node. I've tried many versions of mongoose still gives me same error.
MongoServerSelectionError: getaddrinfo EAI_AGAIN mongo
at Timeout._onTimeout (/home/user/git_folder/project/server/node_modules/mongodb/lib/sdam/topology.js:312:38)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'mongo:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'mongo', port: 27017 },
address: 'mongo:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 53541928,
lastWriteDate: 0,
error: MongoNetworkError: getaddrinfo EAI_AGAIN mongo
at connectionFailureError (/home/user/git_folder/project/server/node_modules/mongodb/lib/cmap/connect.js:375:20)
at Socket.<anonymous> (/home/user/git_folder/project/server/node_modules/mongodb/lib/cmap/connect.js:295:22)
at Object.onceWrapper (node:events:640:26)
at Socket.emit (node:events:520: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)
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined
}
i build frontend (next.js) and backend(express) ,and try to call backend api but fail.
the following is my code:
dockerFile from backend(listen port 3001)
FROM node:16.13-alpine
WORKDIR /backend/
COPY . .
ENV NODE_ENV=production
EXPOSE 3001
RUN npm install -g npm#8.3.0\
&& npm install\
&& npm install typescript -g\
&& npx tsc
CMD [ "node", "./build/index.js" ]
dockerFile from frontend(listen port 3000), api baseUrl is http://node:80/
FROM node:16.13-alpine
WORKDIR /frontend/
ENV PORT 3000
COPY package.json ./
COPY yarn.lock ./
RUN npm install
COPY . ./
EXPOSE ${PORT}
ENTRYPOINT ["npm", "run","dev"]
docker-compose.yml
version: "3.9"
services:
node:
env_file: "./back/.env"
volumes:
- ./test:/backend/test
- ./back/node_modules:/backend/src/node_modules
build:
context: ./back
ports:
- "80:3001"
expose:
- 80
networks:
- testNetwork
next:
depends_on:
- node
build:
context: ./front
ports:
- "3000:3000"
networks:
- testNetwork
volumes:
- ./front/node_modules:/frontend/src/node_modules
- ./test:/frontend/test
networks:
testNetwork:
i can access localhost:80 ,which is working.
but when i access localhost:3000, i got error by next.js as below
next_1 | Error: connect ECONNREFUSED 172.21.0.2:80
next_1 | at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) {
next_1 | type: 'Error',
next_1 | config: {
next_1 | transitional: {
next_1 | silentJSONParsing: true,
next_1 | forcedJSONParsing: true,
next_1 | clarifyTimeoutError: false
next_1 | },
next_1 | transformRequest: [ null ],
next_1 | transformResponse: [ null ],
next_1 | timeout: 0,
next_1 | xsrfCookieName: 'XSRF-TOKEN',
next_1 | xsrfHeaderName: 'X-XSRF-TOKEN',
next_1 | maxContentLength: -1,
next_1 | maxBodyLength: -1,
next_1 | headers: {
next_1 | Accept: 'application/json, text/plain, */*',
next_1 | 'User-Agent': 'axios/0.23.0'
next_1 | },
next_1 | baseURL: 'http://node:80/',
next_1 | method: 'get',
next_1 | url: 'getStaticPath/onlyCategoryRoute'
next_1 | },
next_1 | code: 'ECONNREFUSED',
next_1 | status: null
next_1 | }
thanks for looking
Your application is attempting to connect to port 80 within a docker container but you have port 80 available only on the host computer, within the docker container, it is port 3001.
I have some issue on connect to mongodb with docker and NodeJS driver.
Here is my docker-compose.yml file:
version: "3.3"
services:
mongodb:
image: mongo:4.0.20
ports:
- 27017:27017
command: mongod --replSet rs0
deploy:
replicas: 1
restart_policy:
condition: "on-failure"
And I launch my service with
docker stack deploy -c ./docker-compose.yml --with-registry-auth XXX
Then, when I'm sure mongo is well started, I run:
docker exec $(docker ps -q -f name=mongodb) mongo local --eval "rs.initiate()"
which initialize the replicat set.
Here is my nodejs test file:
const MongoClient = require('mongodb');
(async () => {
let db;
try {
db = (await MongoClient(
'mongodb://localhost:27017/qos',
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)).db();
console.log('connected');
} catch (error) {
console.trace(error)
}
})()
But when I run the test.js file, I see:
Trace: MongoServerSelectionError: getaddrinfo ENOTFOUND 272b05abb632
at Timeout._onTimeout (node_modules/mongodb/lib/core/sdam/topology.js:438:30)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: 'rs0',
maxSetVersion: 1,
maxElectionId: 7fffffff0000000000000001,
servers: Map { 'bcc9e46ea248:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: 7
}
}
at test.js:15:13
I check that 272b05abb632 is the good container id,
and on my docker process I see:
2020-11-10T16:34:49.019360315Z XXX_mongodb.1.awsb46tji1lg#docker-desktop | 2020-11-10T16:34:49.018+0000 I NETWORK [listener] connection accepted from 10.0.0.2:49082 #4 (2 connections now open)
2020-11-10T16:34:49.027564962Z XXX_mongodb.1.awsb46tji1lg#docker-desktop | 2020-11-10T16:34:49.027+0000 I NETWORK [conn4] received client metadata from 10.0.0.2:49082 conn4: { driver: { name: "nodejs", version: "3.6.3" }, os: { type: "Darwin", name: "darwin", architecture: "x64", version: "19.6.0" }, platform: "'Node.js v12.19.0, LE (unified)" }
2020-11-10T16:34:49.033185739Z XXX_mongodb.1.awsb46tji1lg#docker-desktop | 2020-11-10T16:34:49.032+0000 I NETWORK [conn4] end connection 10.0.0.2:49082 (1 connection now open)
I don't understand why with useUnifiedTopology, it's not work :(
I request your help !
I also tried to add mongod.conf in my container via docker-compose, but it doesn't work too:
version: "3.3"
services:
mongodb:
image: mongo:4.0.20
ports:
- 27017:27017
command: mongod --config /etc/mongod.conf
volumes:
- "./mongod.conf:/etc/mongod.conf"
deploy:
replicas: 1
restart_policy:
condition: "on-failure"
security:
authorization: 'enabled'
net:
port: 27017
bindIp: 0.0.0.0 #default value is 127.0.0.1
replication:
replSetName: rs0
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.
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?