NodeJS Mongodb in docker compose = ECONNREFUSED

那年仲夏 提交于 2019-12-06 02:36:38

问题


I try to up a Node.JS container linked with a MongoDB container by docker-compose, but systematically node.js return an ECONNREFUSED error.

The error

nodejs_1   | /code/node_modules/mongoose/node_modules/mongodb/lib/server.js:228
nodejs_1   |         process.nextTick(function() { throw err; })
nodejs_1   |                                   
nodejs_1   | Error: connect ECONNREFUSED
nodejs_1   |     at exports._errnoException (util.js:746:11)
nodejs_1   |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1010:19)

NodeJS code

var db = 'mongodb://database:27017/wondrapi';
mongoose.connect(db);

docker-compose.yml

web:
  build: ./web
  ports:
    - "8080:80"
  links:
    - nodejs
  volumes:
    - ./web:/usr/share/nginx/html:ro
nodejs:
  build: ./api
  ports:
    - "8081:3000"
  links:
    - database
  command: npm start
database:
  image: mongo
  volumes:
    - db:/data/db
  ports:
    - 27017

Dockerfile (./api)

FROM node

ADD package.json /code/
WORKDIR /code
RUN npm install
ADD . /code

How can I solve the error?


回答1:


I solve my problem:

I try to setup my connection (from node) to mongodb before the mongodb server was completely up (it take 5/6 secs for the first start).

So, i just need to retry the connection few times (3/4 times) with 1 sec before each requests from node before mongo accept the request.

var connectWithRetry = function() {
    return mongoose.connect(db, function(err) {
        if (err) {
            console.error('Failed to connect to mongo on startup - retrying in 1 sec', err);
            setTimeout(connectWithRetry, 1000);
        }
    });
};
connectWithRetry();



回答2:


You should use:

docker stack deploy --compose-file <compose-file-name> <app-name>


来源:https://stackoverflow.com/questions/32503116/nodejs-mongodb-in-docker-compose-econnrefused

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!