MongoDB connection error: MongoError: failed to connect to server [localhost:27017]
I have a project which includes a docker setup that I'm trying to get working. My Dockerfile is:
FROM node:8-alpine
EXPOSE 3000
ARG NODE_ENV
ENV NODE_ENV $NODE_ENV
RUN mkdir /app
WORKDIR /app
ADD package.json yarn.lock seed.js /app/
RUN yarn --pure-lockfile
ADD . /app
CMD ["yarn seed"]
CMD ["yarn", "docker:start"]
and my docker-compose:
version: "2"
services:
isawyou-server:
build: .
environment:
- MONGO_URI=mongodb://mongodb:27017/isawyou
volumes:
- .:/app
ports:
- "3000:3000"
depends_on:
- mongodb
mongodb:
image: mongo
ports:
- "27017:27017"
Now, for the docker-compose.test I am trying to set it up according to the instructions of https://docs.docker.com/docker-cloud/builds/automated-testing/ . I basically want to have a different database for testing. I tried different configs but none works. The error I get is:
directory '/data/db/diagnostic.data'
mongodb_1 | 2017-11-21T21:29:27.518+0000 I NETWORK [thread1] waiting for connections on port 27017
mongodb_1 | 2017-11-21T21:29:33.500+0000 I NETWORK [thread1] connection accepted from 172.18.0.4:39460 #1 (1 connection now open)
mongodb_1 | 2017-11-21T21:29:33.509+0000 I NETWORK [conn1] received client metadata from 172.18.0.4:39460 conn1: { driver: { name: "nodejs", version: "2.2.33" }, os: { type: "Linux", name: "linux", architecture: "x64", version: "4.9.49-moby" }, platform: "Node.js v8.9.1, LE, mongodb-core: 2.1.17" }
mongodb_1 | 2017-11-21T21:29:33.527+0000 I NETWORK [thread1] connection accepted from 172.18.0.4:39462 #2 (2 connections now open)
mongodb_1 | 2017-11-21T21:29:33.548+0000 I INDEX [conn1] build index on: isawyou.users properties: { v: 2, unique: true, key: { email: 1 }, name: "email_1", ns: "isawyou.users", background: true }
mongodb_1 | 2017-11-21T21:29:33.568+0000 I INDEX [conn2] build index on: isawyou.refreshtokens properties: { v: 2, key: { token: 1 }, name: "token_1", ns: "isawyou.refreshtokens", background: true }
mongodb_1 | 2017-11-21T21:29:33.568+0000 I INDEX [conn2] build index done. scanned 0 total records. 0 secs
mongodb_1 | 2017-11-21T21:29:33.568+0000 I INDEX [conn1] build index done. scanned 0 total records. 0 secs
isawyou-server_1 | yarn run v1.3.2
isawyou-server_1 | $ cross-env NODE_ENV=production pm2-docker start ./src/index.js
isawyou-server_1 | 0|index | server started on port 3000 (production)
isawyou-server_1 | 0|index | ::ffff:172.18.0.1 - - [21/Nov/2017:21:32:26 +0000] "GET / HTTP/1.1" 404 60 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"
sut_1 | yarn run v1.3.2
sut_1 | $ cross-env NODE_ENV=test nyc --reporter=html --reporter=text mocha --timeout 20000 --recursive src/tests
sut_1 |
sut_1 |
sut_1 | server started on port 3000 (test)
sut_1 | Authentication API
sut_1 | MongoDB connection error: MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
my docker-compose.test currently looks like:
version: "2"
services:
sut:
build: .
command: yarn test
I am having issue while connecting mongodb running outside on local machine, not as mongo container. it is running on localhost:27017
error: Error: Failed to connect to MongoDB. Are you sure your configured Mongo instance is running?
Error details:
{ Error: connect ECONNREFUSED 127.0.0.1:27017
at Object.exports._errnoException (util.js:1020:11)
at exports._exceptionWithHostPort (util.js:1043:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
name: 'MongoError',
message: 'connect ECONNREFUSED 127.0.0.1:27017' }
Make sure MongoDB is up and running in the correct folder.
Just writing "mongod" in the terminal should do it.
MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.
I have the same issue here. I am trying to connect to a mongodb running on atlas. However, the local db connects just fine.
@chileshemartin is your issue resolved or not as i am facing the same error
Yes. Mine was resolved. It turned out that my firewall was blocking my connection. If your have an anti-virus, you can also try to disable it. Some could also blocking the connection.
On Fri, Feb 23, 2018, 11:38 AM Palash gupta [email protected] wrote:
@chileshemartin https://github.com/chileshemartin is your issue resolved or not as i am facing the same error
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/docker/hub-feedback/issues/1255#issuecomment-367958732, or mute the thread https://github.com/notifications/unsubscribe-auth/AOd4pMBQ2JVqMaa1syDEKBDrqhRhHoqIks5tXocdgaJpZM4Qmjdn .
--
Chileshe Martin
yeah man it works thanks! it was pretty hard to detect the error but anyways it works :-D thanks @chileshemartin
{ MongoError: failed to connect to server [127.0.0.1:27107] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27107]
at Pool.
@zykoikaze 上面不是说了么,你看看你是不是开了防火墙
@shawn-tangsc 已经解决了,谢谢啦!
For docker-compose mongo service is up when this starts the container, but inside them mongodb is still starting up (the port 27017 is not available yet and could take some seconds).
I fixed my code using a mongoose (my ODM) connection retry. Here is my code:
Using: node 8.10
docker-compose.yml
version: '3.6'
services:
api:
build: .
ports:
- "8000:8000"
depends_on:
- mongodb
mongodb:
image: mongo
volumes:
- ./data:/data/db
ports:
- "27017:27017"
mongoose.js
// Package
import bluebird from 'bluebird'
import mongoose from 'mongoose'
// Ours
import config from '../config'
// Set mongoose Promise to Bluebird
mongoose.Promise = bluebird
// Retry connection
const connectWithRetry = () => {
console.log('MongoDB connection with retry')
return mongoose.connect(config.db.mongo.uri, config.db.mongo.opts)
}
// Exit application on error
mongoose.connection.on('error', err => {
console.log(`MongoDB connection error: ${err}`)
setTimeout(connectWithRetry, 5000)
// process.exit(-1)
})
mongoose.connection.on('connected', () => {
console.log('MongoDB is connected')
})
if (config.env === 'development') {
mongoose.set('debug', true)
}
const connect = () => {
connectWithRetry()
}
export default { connect }
I hope could fix your issue!
@colkito In mongoose 5.x.x looks like they force you to handle the promise from mongoose.connect() and that equivalent to mongoose.connection.on('error' and mongoose.connection.on('connected'. So little edit based on your code:
mongoose.js
const options = {
autoIndex: false, // Don't build indexes
reconnectTries: 30, // Retry up to 30 times
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
}
const connectWithRetry = () => {
console.log('MongoDB connection with retry')
mongoose.connect("mongodb://mongo:27017/test", options).then(()=>{
console.log('MongoDB is connected')
}).catch(err=>{
console.log('MongoDB connection unsuccessful, retry after 5 seconds.')
setTimeout(connectWithRetry, 5000)
})
}
connectWithRetry()
good point thanks!
I am trying to deploy Mean Stack application in google cloud platform but I am getting the below error which is unable to connect to mongo DB
MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.
In my situation when I tried to docker-compose up the logs were saying that node was unable to connect to Mongo and I believe mongod is run by the mongo container by default so no issues there.
So what I needed to do was build again with:
docker-compose build
failed to connect to server [127.0.01:27017] on first connect [MongoError: getaddrinfo ENOTFOUND 127.0.01 127.0.01:27017]' }
Just going to leave my own take, on @viane's excellent answer. I used the promise-retry library, which worked beautifully!
const promiseRetry = require('promise-retry')
const options = {
useNewUrlParser: true,
reconnectTries: 60,
reconnectInterval: 1000,
poolSize: 10,
bufferMaxEntries: 0 // If not connected, return errors immediately rather than waiting for reconnect
}
const promiseRetryOptions = {
retries: options.reconnectTries,
factor: 2,
minTimeout: options.reconnectInterval,
maxTimeout: 5000
}
const connect = () => {
return promiseRetry((retry, number) => {
logger.info(`MongoClient connecting to ${url} - retry number: ${number}`)
return MongoClient.connect(url, options).catch(retry)
}, promiseRetryOptions)
}
module.exports = { connect }
go to task manger and run mongoDb service.

@Abhinay-g Why we need run MongoDB? The mongo is inside a container too. I try the script from @colkito but didn't work too. The application did many attempts but all connection fail.
I came across the same issue but mine is mongodb://mongodb:27017/, should be mongodb://mongo:27017/. ... 😞