无法到达mongo db容器

时间:2019-11-19 07:13:18

标签: node.js mongodb docker docker-compose

我试图通过此article实现基于dockergo mongo / node的应用。

docker-compose.yml

version: '3'
services:
  gecar_app:
    build: 
      context: . 
      dockerfile: Dockerfile.gecars
    restart: always
    ports:
      - 3000:3000
    depends_on:
      - mongo
    command: /usr/app/initAndStartService.sh
  mongo:
    container_name: mongo
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"

Dockerfile.gercars

FROM node:latest
RUN mkdir -p /usr/app
WORKDIR /usr/app
COPY src/ /usr/app/src/
COPY package.json /usr/app/package.json
COPY webpack.config.js /usr/app/webpack.config.js
COPY tsconfig.json /usr/app/tsconfig.json
COPY initAndStartService.sh /usr/app/initAndStartService.sh
RUN yarn
RUN yarn build

RUN ["chmod", "+x", "/usr/app/initAndStartService.sh"]

initAndStartService.sh

#!/bin/sh
curl 127.0.0.1:27017

但是在运行docker-compose up时得到以下信息:

mongo        | 2019-11-19T06:13:21.682+0000 I  NETWORK  [initandlisten] Listening on 0.0.0.0
mongo        | 2019-11-19T06:13:21.683+0000 I  NETWORK  [initandlisten] waiting for connections on port 27017

...................

gecar_app_1  |                                  Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (7) Failed to connect to 127.0.0.1 port 27017: Connection refused

如果我正确认识到这种情况,gecar_app_1容器可以t reach mongo`容器。

2 个答案:

答案 0 :(得分:0)

  

depends_on

     

服务之间的快速依赖关系,服务依赖关系导致   以下行为:

docker-compose up starts services in dependency order. In the following example, db and redis are started before web.

docker-compose up SERVICE automatically includes SERVICE’s dependencies. In the following example, docker-compose up web also
     

创建并启动db和redis。

docker-compose stop stops services in dependency order. In the following example, web is stopped before db and redis.

换句话说,当您想与mongo容器通信时,您要做的就是根据容器服务命名将其称为mongo

因此,来自 gecar_app 容器的curl mongo:27017可以解决问题

答案 1 :(得分:0)

127.0.0.1是一个环回地址,这意味着,当您在curl 127.0.0.1:27017容器上运行gecar_app时,您尝试连接到自身,但是gecar_app没有任何服务在27017端口上运行。您需要连接的是mongo服务(我认为是这样)。

您使用depends_on等到mongo服务启动,然后启动gecar_app容器(好点),现在mongo将成为主机名,并且gecar_app可以通过mongo“域”连接到mongo

但是,gecar_app可能已经在mongodb服务之前启动,那么您必须确保mongo已经服务。您可以使用healthcheck属性来做到这一点。

最后, docker-compose.yml

version: '3'
services:
  gecar_app:
    build: 
      context: . 
      dockerfile: Dockerfile.gecars
    restart: always
    ports:
      - 3000:3000
    depends_on:
      - mongo
    command: /usr/app/initAndStartService.sh
  mongo:
    container_name: mongo
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
    healthcheck:
      test: echo 'db.runCommand("ping").ok' | mongo mongo:27017/test --quiet 1
      interval: 3s
      timeout: 5s
      retries: 5

initAndStartService.sh

#!/bin/sh
curl mongo:27017