hub-feedback icon indicating copy to clipboard operation
hub-feedback copied to clipboard

MongoDB connection error: MongoError: failed to connect to server [localhost:27017]

Open gplusdotgr opened this issue 9 years ago • 66 comments

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

gplusdotgr avatar Nov 21 '17 22:11 gplusdotgr

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' }

ravigupta87 avatar Dec 19 '17 14:12 ravigupta87

Make sure MongoDB is up and running in the correct folder.

Just writing "mongod" in the terminal should do it.

Gjelten avatar Jan 01 '18 22:01 Gjelten

MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]

at Pool. (/home/ravi/Release-v3.4.1/nuve/node_modules/mongodb-core/lib/topologies/server.js:329:35) at emitOne (events.js:96:13) at Pool.emit (events.js:188:7) at Connection. (/home/ravi/Release-v3.4.1/nuve/node_modules/mongodb-core/lib/connection/pool.js:280:12) at Connection.g (events.js:291:16)

penseurtank avatar Feb 07 '18 12:02 penseurtank

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 avatar Feb 08 '18 10:02 chileshemartin

@chileshemartin is your issue resolved or not as i am facing the same error

palashgupta98 avatar Feb 23 '18 09:02 palashgupta98

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

chileshemartin avatar Feb 23 '18 10:02 chileshemartin

yeah man it works thanks! it was pretty hard to detect the error but anyways it works :-D thanks @chileshemartin

palashgupta98 avatar Feb 23 '18 10:02 palashgupta98

{ MongoError: failed to connect to server [127.0.0.1:27107] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27107] at Pool. (D:\test\各语言汇总\node\node06\node_modules\mongodb-core\lib\topologies\server.js:503:11) at emitOne (events.js:96:13) at Pool.emit (events.js:188:7) at Connection. (D:\test\各语言汇总\node\node06\node_modules\mongodb-core\lib\connection\pool.js:326:12) at Connection.g (events.js:292:16) at emitTwo (events.js:106:13) at Connection.emit (events.js:191:7) at Socket. (D:\test\各语言汇总\node\node06\node_modules\mongodb-core\lib\connection\connection.js:245:50) at Socket.g (events.js:292:16) at emitOne (events.js:96:13) name: 'MongoNetworkError', message: 'failed to connect to server [127.0.0.1:27107] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27107]' } 请问这个到底是怎么解决的,我还没找到原因!谢谢!

zykoikaze avatar Apr 08 '18 09:04 zykoikaze

@zykoikaze 上面不是说了么,你看看你是不是开了防火墙

shawn-tangsc avatar Apr 17 '18 03:04 shawn-tangsc

@shawn-tangsc 已经解决了,谢谢啦!

zykoikaze avatar Apr 23 '18 07:04 zykoikaze

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 avatar Apr 26 '18 00:04 colkito

@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()

viane avatar May 07 '18 04:05 viane

good point thanks!

colkito avatar May 08 '18 00:05 colkito

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. (/app/node_modules/mongodb-core/lib/topologies/server.js:336) at emitOne (events.js:116) at Pool.emit (events.js:211) at Connection. (/app/node_modules/mongodb-core/lib/connection/pool.js:280) at Object.onceWrapper (events.js:317) at emitTwo (events.js:126) at Connection.emit (events.js:214) at Socket. (/app/node_modules/mongodb-core/lib/connection/connection.js:189) at Object.onceWrapper (events.js:315) at emitOne (events.js:116) at Socket.emit (events.js:211) at emitErrorNT (internal/streams/destroy.js:64) at _combinedTickCallback (internal/process/next_tick.js:138) at process._tickCallback (next_tick.js:180)

ravi-nrk avatar May 15 '18 16:05 ravi-nrk

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

RFSync avatar Jun 05 '18 19:06 RFSync

failed to connect to server [127.0.01:27017] on first connect [MongoError: getaddrinfo ENOTFOUND 127.0.01 127.0.01:27017]' }

azizsallam avatar Aug 19 '18 23:08 azizsallam

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 }

nickgrealy avatar Aug 24 '18 03:08 nickgrealy

go to task manger and run mongoDb service. image

Abhinay-g avatar Sep 11 '18 15:09 Abhinay-g

@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.

fmassicano avatar Nov 09 '18 14:11 fmassicano

I came across the same issue but mine is mongodb://mongodb:27017/, should be mongodb://mongo:27017/. ... 😞

williamhqs avatar Nov 12 '18 16:11 williamhqs