gpt4 book ai didi

node.js - Docker MongoDB收到元数据后立即关闭连接

转载 作者:行者123 更新时间:2023-12-02 21:08:46 24 4
gpt4 key购买 nike

我试图用两个容器组成docker app:

  • mongo
  • 应用程序

  • Mongo容器工作正常,而应用程序无法连接到mongo。 node.js应用程序和mongostat都不能。奇怪的是,我尝试在装有Win10的两台计算机上运行该项目,并且在另一台计算机上正常运行。

    这些是当我从应用程序容器运行 node app.jsmongostat --uri "mongodb://mongo:27017/project"时来自mongo容器的日志:
    2019-05-22T09:33:52.225+0000 I NETWORK  [conn17] received client metadata from 192.168.96.2:42916 conn17: { driver: { name: "nodejs", version: "3.1.10" }, os: { type: "Linux", name: "linux", architecture: "x64", version: "4.9.125-linuxkit" }, platform: "Node.js v10.15.3, LE, mongodb-core: 3.1.9" }
    2019-05-22T09:33:52.231+0000 I NETWORK [conn17] end connection 192.168.96.2:42916 (0 connections now open)

    这意味着两个容器都可以看到对方,因此.yml文件应该可以。如果问题出在代码上,那么它就不能同时在两台计算机上工作。

    Dockerfile:
    FROM node:10.15.3-alpine
    RUN apk update && apk --no-cache --virtual build-dependencies add python make g++ && apk del build-dependencies
    RUN mkdir -p /home/node/app && chown -R node:node /home/node/app
    WORKDIR /home/node/app
    COPY package*.json ./
    USER node
    COPY --chown=node:node . .
    ENV NPM_CONFIG_PREFIX=/home/node/.npm-global
    RUN npm install
    EXPOSE 3000
    CMD ["node", "app.js"]

    docker-compose.yml:
    version: "3.5"
    services:
    app:
    container_name: app
    restart: always
    build: .
    ports:
    - "3000:3000"
    networks:
    - mongo
    mongo:
    restart: always
    container_name: mongo
    image: mongo
    expose:
    - 27017
    volumes:
    - mongodata:/data/db
    ports:
    - '27017:27017'
    networks:
    - mongo
    volumes:
    mongodata:
    networks:
    mongo:
    external: true

    来自app.js的代码段:
    MongoClient.connect('mongodb://mongo:27017/project', {useNewUrlParser: true}, (err, client) => {
    if (err) throw err; //throws MongoNetworkError: failed to connect to server [mongo:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND mongo mongo:27017]
    console.log("connected");
    client.close();//at the moment this line is not being reached because of throw err;
    });```

    最佳答案

    如果在连接到mongo数据库之前在应用程序中插入“sleep 10”是否有帮助?如果是这样,添加类似wiatforit(https://github.com/maxcnunes/waitforit)的内容可能会有所帮助。

    关于node.js - Docker MongoDB收到元数据后立即关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56254218/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com