无法将Mongodb连接到Docker中的Springboot容器

问题描述:

我尝试了许多选项来从docker访问MongoDB映像.它在docker外部运行良好,但是如果我在docker容器中运行应用程序,则会显示错误.下面提到的是错误的屏幕截图.此外,还分享了我正在运行的连接和命令代码.

I have tried many options to access the MongoDB image from docker. It works fine outside the docker but If I run the application in docker container it shows me an error. Mentioned below are screenshots of errors. Also, shared the code of connection and commands which I am running.

运行Spring Boot应用程序时发生异常

Exception while running spring boot application

Mongo Db容器运行

Mongo Db Container Running

用于连接docker MongoDB映像的Java代码

Java Code used for connecting docker MongoDB image

MongoClient mongo = new MongoClient("mongodb//db", 27017));

我也尝试了其他选择

MongoClient mongo = new MongoClient("localhost", 27017));

如果我直接运行jar,但在docker容器中无法运行,效果很好.

It works fine if I run the jar directly but doesn't work inside the docker container.

请为我提供解决方案.

问题

您正在尝试使用错误的IP/主机名访问数据库.如您所见,访问spring容器中的localhost将解析为该容器,并且那里没有27017端口在监听.在docker主机上运行jar时,它具有27017端口可用,这就是为什么它可以工作的原因.

Problem

You're trying to access the DB with wrong IP/hostname. As you can see, accessing localhost in the spring container would resolve to that container and there's no 27017 port listening there. When you run the jar on docker host, it has 27017 port available, that's why it works.

您可以在docker run命令中使用--hostname标志来设置数据库容器的主机名,以便您可以使用主机名从Spring容器连接到它.

You can use --hostname flag in docker run command to set the hostname of DB container so that you can connect to it from the Spring container using the hostname.

但是,更好的解决方案是使用docker-compose文件,然后使用docker-compose up启动容器.

The better solution, however, is to use a docker-compose file and start the containers using docker-compose up.

首先使用

MongoClient mongo = new MongoClient("db", 27017));

在您的Spring代码中,并为您的代码建立一个图像.

in your Spring code and build an image of your code.

然后,请按照以下步骤启动容器:

Afterward, follow the steps below to start the containers:

创建一个名为docker-compose.yml的文件,其内容如下:

Create a file named docker-compose.yml with following content:

version: "2.1"
services:
  app:
    # replace imageName with your image name (block in your case)
    image: imageName:tag
    ports:
      - 9876:4000 # Replace the port of your application here if used
    depends_on: 
      - db
  db:
    image: mongo
    volumes:
      - ./database:/data
    ports:
      - "27017:27017"   

B)运行撰写文件

执行以下命令以运行撰写文件: docker-compose up -d

B) Run the compose file

Execute following command to run the compose file: docker-compose up -d