泊坞窗中的NodeJS Mongodb撰写= ECONNREFUSED [英] NodeJS Mongodb in docker compose = ECONNREFUSED

查看:66
本文介绍了泊坞窗中的NodeJS Mongodb撰写= ECONNREFUSED的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试通过docker-compose建立与MongoDB容器链接的Node.JS容器,但是系统地node.js返回ECONNREFUSED错误.

I try to up a Node.JS container linked with a MongoDB container by docker-compose, but systematically node.js return an ECONNREFUSED 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代码

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

docker-compose.yml

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)

Dockerfile (./api)

FROM node

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

如何解决该错误?

推荐答案

我解决了我的问题:

我尝试在mongodb服务器完全启动之前(从节点启动)建立到mongodb的连接(第一次启动需要5/6秒).

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

因此,在mongo接受节点的每个请求之前,我只需要在1秒钟内重试几次连接(3/4次)

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

这篇关于泊坞窗中的NodeJS Mongodb撰写= ECONNREFUSED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆