Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
814 views
in Technique[技术] by (71.8m points)

node.js - 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 127.0.0.1:27017]

This is my docker-compose

version: '3.4'

services:
  db:
    image: mongo:latest
    ports:
      - '27017:27017'

  rest-api-node:
    build: .
    ports:
      - '5000:5000'
    links:
      - 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
mongoose.connect('mongodb://localhost/demo')
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. (/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 |
message: 'failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]' }

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 127.0.0.1:27017 only from host machine. In order to access it from NodeJS backend container you should use db:27017.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...