title: MongoDB on with Docker "failed to connect to server [localhost:27017] on first connect "
body: <p>I am using mongoDB with and NodeJS backend. The Problem is I am getting the following error</p>
  
  <blockquote>
    <p>node:16) UnhandledPromiseRejectionWarning: MongoNetworkError: failed
    to connect to server [localhost:27017] on first connect
    [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]</p>
  </blockquote>
  
  <p>This is my docker-compose</p>
  
  <pre><code>version: '3.4'
  
  services:
    db:
      image: mongo:latest
      ports:
        - '27017:27017'
  
    rest-api-node:
      build: .
      ports:
        - '5000:5000'
      links:
        - db
      restart: on-failure
  </code></pre>
  
  <p>I have tried with <code>depends_on</code> as well , was not working.</p>
  
  <p>On backend I am mongoose as a middleware to communicate with DB. this is the part of my <code>index.js</code></p>
  
  <pre><code>mongoose.Promise = global.Promise
  mongoose.connect('mongodb://localhost/demo')
  app.listen(port, () =&gt; console.log("live"))
  </code></pre>
  
  <p>I have tried using promise as well , no change though. Please Help me out.
  Thanks in advance </p>
  
  <p>complete error log</p>
  
  <blockquote>
    <p>at Pool.
    (/app/node_modules/mongodb-core/lib/topologies/server.js:505:11)
    rest-api-node_1  |     at Pool.emit (events.js:180:13) rest-api-node_1
    |     at Connection.
    (/app/node_modules/mongodb-core/lib/connection/pool.js:329:12)
    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.
    (/app/node_modules/mongodb-core/lib/connection/connection.js:245:50)
    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  |<br>
    message: 'failed to connect to server [localhost:27017] on first
    connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]' }</p>
  </blockquote>