Docker-Compose:无法将NodeJS与Mongo和Redis连接[拒绝连接]

时间:2019-05-24 09:40:35

标签: node.js mongodb docker redis docker-compose

我正在使用3种服务:

  • api-knotain [主要api服务]
  • api-mongo [用于api服务的mongo数据库]
  • api-redis [用于api服务的redis]

用于api-knotain的Dockerfile如下所示

[ 'array.*.start_date' ]

我的docker-compose文件如下:

FROM node:latest
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
RUN npm install
# If you are building your code for production
# RUN npm ci --only=production
# Bundle app source
COPY . .
CMD [ "npm", "start" ]

runnin

  • docker-compose build
  • docker-compose up

输出:

version: '3.3'
services:
  api-knotain:
    container_name: api-knotain
    restart: always
    build: ../notify.apiV2/src
    ports:
      - "7777:7777"
    links:
      - api-mongo
      - api-redis
    environment:
      - REDIS_URI=api-redis
      - REDIS_PORT=32770
      - MONGO_URI=api-mongo
      - MONGO_PORT=27017
      - RESEED=true
      - NODE_TLS_REJECT_UNAUTHORIZED=0
  api-mongo: 
    container_name: api-mongo
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
  api-redis:
    container_name: api-redis
    image: "redis:alpine"
    ports:
      - "32770:32770"

mongo和redis均无法连接。 我尝试了以下操作:

  • 使用localhost而不是容器名称
  • 使用其他端口
  • 使用暴露vs端口

总是具有相同的结果

注意:

  • 我可以通过本地cli'localhost:port'毫无问题地连接到mongo和redis

我想念什么?

3 个答案:

答案 0 :(得分:0)

redis和mongo容器的启动可能晚于您的应用程序,因此您的应用程序将看不到它们。 To counter this you must wait for those services to be ready.

links is a legacy feature of Docker。如果要将数据库和Redis容器与外部网络隔离,则应使用depends_on控制启动顺序,并使用user-defined networks

答案 1 :(得分:0)

version: '3.3'
services:
  api-knotain:
    depends_on:
      - api-mongo
      - api-redis
    container_name: api-knotain
    restart: always
    build: ../notify.apiV2/src
    ports:
      - "7777:7777"
    links:
      - api-mongo
      - api-redis
    environment:
      - REDIS_URI=api-redis
      - REDIS_PORT=32770
      - MONGO_URI=api-mongo
      - MONGO_PORT=27017
      - RESEED=true
      - NODE_TLS_REJECT_UNAUTHORIZED=0
  api-mongo: 
    container_name: api-mongo
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
  api-redis:
    container_name: api-redis
    image: "redis:alpine"
    ports:
      - "32770:32770"

答案 2 :(得分:0)

看起来Depend_on在3.3版本的docker compose中无法正常工作。在将版本更新为3.7之后,所有内容都可以完美运行,而无需更改撰写文件。