无法在 docker 中将 Mongodb 连接到 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
标志来设置 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