使用Loopback和Mongodb的Docker组合无法连接mongdb

时间:2017-11-15 18:15:11

标签: mongodb docker-compose loopback

我最近一直在学习码头工作,我无法在我的loopback api和mongodb之间建立联系。该应用程序在本地开发环境中正常工作。使用docker-compose,我的mongodb服务器在localhost:27017运行,而我的react-frontend在localhost:3000服务,看起来很好。只有环回无法连接到mongodb并引发以下错误:

loopback_1  | Web server listening at: http://localhost:8080
loopback_1  | Browse your REST API at http://localhost:8080/explorer
loopback_1  | Connection fails: MongoError: failed to connect to server 
[localhost:27017] on first connect [MongoError: connect ECONNREFUSED 
127.0.0.1:27017]
loopback_1  | It will be retried for the next request.
loopback_1  | 
loopback_1  | /opt/src/app/node_modules/mongodb/lib/mongo_client.js:421
loopback_1  |           throw err
loopback_1  |           ^
loopback_1  | MongoError: failed to connect to server [localhost:27017] 
on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
loopback_1  |     at Pool.<anonymous> 
(/opt/src/app/node_modules/mongodb-core/lib/topologies/server.js:336:35)

以下是 Loopback-API Dockerfile

FROM node:6

RUN mkdir -p /opt/src/app

WORKDIR  /opt/src/app

COPY package.json /opt/src/app

RUN npm cache clean

RUN npm install

COPY . /opt/src/app

EXPOSE 8080

CMD ["npm", "start"]

我的 docker-compose 文件如下所示:

    version: '3.0' # specify docker-compose version

# Define the services/containers to be run
services:
  database: # name of first service
      image: mongo # specify the image to build container from
      ports:
        - "27017:27017" # specify port forwarding

  loopback: # name of second service
      build: myapp_backend # specify the directory of the Dockerfile
      ports:
        - "8080:8080" # specify port mapping
      links:
        - database # link this service to the database service

  react: # name of third service
      build: myapp_frontend # specify the directory of the Dockerfile
      ports:
        - "3000:3000" #specify port mapping

最后,loopback-api中的 datasource 文件如下所示:

    {
  "db": {
    "host": "localhost",
    "port": 27017,
    "url": "",
    "database": "test",
    "password": "",
    "name": "mongoDS",
    "user": "",
    "connector": "mongodb"
  }
}

1 个答案:

答案 0 :(得分:2)

您的数据源文件应该包含:

"host": "database" ...

因为在docker-compose.yml中你将mongo容器链接到database的环回,所以它不是localhost。请记住,您正在尝试从loopback docker容器连接到mongo。此外,您应确保在环回之前启动mongo,因此将depends_on: database添加到docker-compose.yml中的环回服务。