且构网

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

无法在 docker 中将 Mongodb 连接到 Springboot 容器

更新时间:2022-11-30 11:27:24

问题

您尝试使用错误的 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 标志来设置 DB 容器的主机名,以便您可以使用主机名从 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