MERN堆栈无法连接到Docker容器的数据库

时间:2020-09-04 07:58:03

标签: node.js reactjs docker docker-compose mern

美好的一天...关于使用dockerfiles和docker-compose.yml在docker上集成MERN堆栈Web应用程序。.localhost:8000是我的后端,也是localhost:3000是我的前端端口..我正在本地运行。.mongo上的凭据正确。.然后将网络放入docker-compose和驱动程序:“ bridge”,在同一网络上..在我构建容器并在docker上运行应用程序之后。 。错误如下:

[0] [http-server] listening: http://localhost:8000/
[1] ℹ 「wds」: Project is running at http://172.20.0.3/
[1] ℹ 「wds」: webpack output is served from
[1] ℹ 「wds」: Content not from webpack is served from /maint/client/public
[1] ℹ 「wds」: 404s will fallback to /
[1] Starting the development server...
[1]
[0] connect ECONNREFUSED 127.0.0.1:27017
[0] ERROR: Cannot connect to the database
[0] Exiting now...
[0] [nodemon] app crashed - waiting for file changes before starting...

我的dockerfiles:

# get the base node image
FROM node:10.15.2

# set the working dir for container
WORKDIR /maint

# copy the json file first
COPY ./package.json /maint

RUN "npm ci"

# copy other project files
COPY . .

# build the folder
CMD [ "npm", "run", "start" ]

并在我的docker-compose-local.yml内部

version: '3'
services:
    maint:
      build:
        context: .
        dockerfile: Dockerfile.dev
      command: npm run dev
      container_name: mat-docker
      volumes:
        - ./:/maint
        - /maint/node_modules
      ports:
        - "3000:3000"
      depends_on:
        - mongo
      networks:
        - app-network
    mongo:
      image: mongo
      container_name: mat-dockerdb
      ports:
        - "27017:27017"
      env_file: .env
      environment:
        - MONGO_HOST:$MONGO_HOST
        - MONGO_DB:$MONGO_DB
        - MONGO_USERNAME:"admin"
        - MONGO_PASSWORD:"password123"
      networks:
        - app-network

networks:
  app-network:
    driver: bridge

1 个答案:

答案 0 :(得分:-1)

仅通过使用主机网络,您可以更轻松地完成此操作。这样,您的主要服务和mongo实例将使用与后端相同的主机网络。这是一个摘要撰写应用程序的示例

 version: "2"
 services:
 app:
    container_name: app
    network_mode: host
    restart: always
    build: .
    ports:
      - "3000:3000”
    depends_on:
      - mongo
 mongo:
    container_name: mongo
    image: mongo
    network_mode: host
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"