NodeJS和Mongodb在docker compose中连接失败=ECONNREFUSED。

8
我尝试通过docker-compose将一个Node.JS容器与一个MongoDB容器连接起来,但是系统性地,node.js返回了ECONNREFUSED错误。
错误信息:
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

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

如何解决这个错误?
2个回答

10

我解决了我的问题:

我尝试在MongoDB服务器完全启动之前(首次启动需要5/6秒)设置来自节点的连接。

所以,我只需要在MongoDB接受请求之前用节点从1秒开始重新尝试连接几次(3/4次)即可。

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

3
您还可以使用类似 wait-for-it 或 dockerize 的工具。例如:entrypoint: ./wait-for-it.sh mongo:27017 -- npm start - antimatter

0

你应该使用:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接