MongoDB on with Docker "failed to connect to server [localhost:27017] on first connect "


I am using mongoDB with and NodeJS backend. The Problem is I am getting the following error

node:16) UnhandledPromiseRejectionWarning: MongoNetworkError: failed
to connect to server [localhost:27017] on first connect
[MongoNetworkError: connect ECONNREFUSED]

This is my docker-compose

version: '3.4'

    image: mongo:latest
      - '27017:27017'

    build: .
      - '5000:5000'
      - db
    restart: on-failure

I have tried with depends_on as well , was not working.

On backend I am mongoose as a middleware to communicate with DB. this is the part of my index.js

mongoose.Promise = global.Promise
app.listen(port, () => console.log("live"))

I have tried using promise as well , no change though. Please Help me out.
Thanks in advance

complete error log

at Pool.
rest-api-node_1 | at Pool.emit (events.js:180:13) rest-api-node_1
| at Connection.
rest-api-node_1 | at Object.onceWrapper (events.js:272:13)
rest-api-node_1 | at Connection.emit (events.js:180:13)
rest-api-node_1 | at Socket.
rest-api-node_1 | at Object.onceWrapper (events.js:272:13)
rest-api-node_1 | at Socket.emit (events.js:180:13)
rest-api-node_1 | at emitErrorNT
(internal/streams/destroy.js:64:8) rest-api-node_1 | at
process._tickCallback (internal/process/next_tick.js:178:19)
rest-api-node_1 | name: ‘MongoNetworkError’, rest-api-node_1 |
message: ‘failed to connect to server [localhost:27017] on first
connect [MongoNetworkError: connect ECONNREFUSED]’ }


By default Compose sets up a single network for your app. Each
container for a service joins the default network and is both
reachable by other containers on that network, and discoverable by
them at a hostname identical to the container name.

According to your docker-compose.yaml file you can access you mongo container on only from host machine.
In order to access it from NodeJS backend container you should use db:27017.

Answered By – nickgryg

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.