MongoError:第一次连接时无法连接到服务器[mongo:27017]

时间:2018-06-18 23:05:26

标签: mongodb docker

Docker配置:

FROM node:8
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 8080
CMD [ "npm", "start" ]

Docker撰写:

version: "2"
services:
  web:
    build: .
    depends_on:
    - mongo
  mongo:
    image: mongo
    ports:
    - "27017:27017"

的package.json:

{
  "name": "docker_web_app",
  "version": "1.0.0",
  "description": "",
  "author": "Stepan Yakovenko <stiv.yakovenko@gmail.com>",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {"express": "^4.16.1","mongodb": "~3.0.1","monk": "~6.0.5" }
}

server.js:

var mongo = require('mongodb');
var monk = require('monk');
var db = monk('mongo:27017/nodetest1');
db.then(function(){console.log("hello"});

大部分时间都有效,但是如果我清除docker缓存,通常它不起作用并给我这个:

web_1    | (node:15) UnhandledPromiseRejectionWarning: MongoError: failed to connect to server [mongo:27017] on first connect [MongoErr
or: connect ECONNREFUSED 172.18.0.2:27017]

根本原因我认为docker的 depends_on 并不能保证mongo已经开始监听,因为在这种情况下我会在发生此错误后收到来自mongo的监听消息。我怎样才能解决这个问题? docker对这种情况有什么解决方法吗?或者我怎么能让mongo尝试永远连接?

感谢名单

2 个答案:

答案 0 :(得分:1)

这是示例重新连接代码,对我有用:

var connect = function () {
    var db = monk('mongo:27017/nodetest1');
    db.then(function () {
        console.log("connected");
    }).catch(function () {
        // sometimes node starts before mongo, so we have to reconnect in case of error
        connect();
    });
};
connect();

答案 1 :(得分:0)

使用网络

以下是没有docker-compose的示例:

# Create the network
docker network create myapp

# Launch mongo
docker run -d --name mongo --network=myapp mongo

# Launch Web
docker run -d --name web --network=myapp -p 8080:8080 myAppNameBuilt

无论如何,这是实施重试连接

的好方法