且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-30 11:23:11

问题

您正在尝试使用错误的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