无法从其他Docker容器连接到MongoDB容器 [英] Can't connect to MongoDB container from other Docker container

查看:105
本文介绍了无法从其他Docker容器连接到MongoDB容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个通过Docker compose链接在一起的容器,我可以使用主机名从包含node.js应用程序的容器成功ping包含MongoDB的容器.但是,当涉及到实际连接到数据库时,node.js会告诉我该连接被拒绝.如果有帮助,我正在使用Docker for Mac.

I have two containers linked together by Docker compose and I can successfully ping the container containing MongoDB from the one containing my node.js app using the hostname. However, when it comes to actually connecting to the database, node.js tells me the connection is refused. I am using Docker for Mac if that helps.


    mongoose.connect("mongodb://mongo", {server: {auto_reconnect: true}}).catch(error => {
            console.log("DB CONNECTION ERROR");
            console.log(error)
        });


这是我的docker-compose.yml文件:

Here is my docker-compose.yml file:


    version: "3"

    services:
      mongo:
        image: mongo:latest
        volumes:
          - ./db:/data/db
        restart: always
        expose:
          - 27017
        ports:
          - 27017:27017
        container_name: mongo

      goose:
        depends_on:
          - mongo
        build: .
        volumes:
          - ./app/server/templates:/usr/src/app/app/server/templates
        expose:
          - 3005
        restart: always
        ports:
          - 3005:3005
        container_name: goose-compose

推荐答案

我有一个类似构建的应用程序,它在两个单独的容器中使用flask和mongodb.我注意到您的撰写和我的撰写之间的区别是,每个容器都有提到的卷,但是没有定义卷,就像这样:

I have a similarly built app using flask and mongodb in two separate containers. One difference that I notice between your compose and mine, is that you have volumes mentioned for each container, but no volume definition, like so:

version: "3"
services:
  web:
    image: jzakilla/bookfinderpy
    command: nginx -g "daemon off;"
    container_name: webapp
    ports:
      - 80:80
      - 443:443 # expose internal container ports to host
  db:
    image: mongo
    container_name: mongodb
    ports:
      - 27017:27017
    volumes:
      - book_db:/data/db
volumes:
  book_db:
    driver: local  

没有卷部分,没有驱动程序告诉容器如何访问数据,我想容器会旋转,但实际上无法启动mongo服务,从而给您带来拒绝的错误.

Without a volume section, and a driver to tell the container how to access the data I would imagine the container would spin up, but not actually be able to start the mongo service, thus giving you a denied error.

这篇关于无法从其他Docker容器连接到MongoDB容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆