[英]Connect To Docker Compose MongoDb Via Spring boot application
My web app can't connect to the MongoDB container我的 Web 应用程序无法连接到 MongoDB 容器
here are my application.yml这是我的 application.yml
spring:
data:
mongodb:
uri: mongodb://mongo:27017
host: mongo
port: 27017
database: my-db-name
and this is my Docker-Compose这是我的 Docker-Compose
version: "3"
services:
java:
build:
context: ./
ports:
- "8080:8080"
links:
- mongo
depends_on:
- mongo
networks:
- shared-net
mongo:
image: 'mongo'
ports:
- 27017:27017
hostname: mongo
volumes:
- ./data/db:/data/db
networks:
- shared-net
networks:
shared-net:
driver: bridge
and this is the Dockerfile wrote for running java这是为运行 java 而编写的 Dockerfile
FROM openjdk:11
COPY ./code/lemon-backend/target/lemon-0.0.1-SNAPSHOT.jar /usr/src/
WORKDIR /usr/src/
EXPOSE 8080
CMD ["java", "-jar", "lemon-0.0.1-SNAPSHOT.jar"]
I can't even build the application using these options I get this exception:我什至无法使用这些选项构建应用程序,我收到此异常:
org.mongodb.driver.cluster: Exception in monitor thread while connecting to server mongo:27017
if possible try giving solutions with docker-compose, thanks如果可能,请尝试使用 docker-compose 提供解决方案,谢谢
OLD VERSION ANSWER旧版答案
IMPORTANT NOTE: older versions of MongoDB ignore this configuration in application.properties
, proceed ahead & use the new solutions I added重要说明:旧版本的 MongoDB 忽略application.properties
此配置,继续使用我添加的新解决方案
This workaround is used for old versions of spring and mongo that ignore the normal configuration (other than uri)此解决方法用于忽略正常配置(uri 除外)的旧版本 spring 和 mongo
. . I had a warning that this property cant be resolved but hopefully, it worked :)我有一个警告说这个属性无法解决,但希望它有效:)
dockerspring.data.mongodb.uri= mongodb://<your_mongodb_container_name>:27017/<name_of_your_db>
the mongodb part is not changeable but mongo before the port number is actually the name of the container witch you have specified in your docker-compose mongodb 部分不可更改,但端口号之前的 mongo 实际上是您在 docker-compose 中指定的容器名称
SPRING BOOT SOLUTION弹簧启动解决方案
spring:
data:
mongodb:
host: <mongo-db-container-name>
port: <mongo-db-port>
database: <database-name>
DOCKER SOLUTION泊坞窗解决方案
In Your Dockerfile Add This Option For Executing Java在您的 Dockerfile 中添加此选项以执行 Java
ENTRYPOINT [“java”,”-Dspring.data.mongodb.uri=mongodb://mongo:27017/name_of_your_db”, “-Djava.security.egd=file:/dev/./urandom”,”-jar”,”/<name_of_your_app>.jar”]
Linking Java And Mongo Containers + Giving Them Names链接 Java 和 Mongo 容器 + 给它们命名
here this is my final docker-compose.yml, I hope that it helps you这是我最后的 docker-compose.yml,希望对你有帮助
version: "3"
services:
java:
build:
context: ./
ports:
- "8080:8080"
container_name: java
links:
- mongo
depends_on:
- mongo
networks:
- shared-net
mongo:
image: 'mongo'
ports:
- 27017:27017
container_name: mongo
volumes:
- /home/sinoed/data/db:/data/db
networks:
- shared-net
networks:
shared-net:
driver: bridge
Compare this version and the one specified in the question carefully仔细比较这个版本和问题中指定的版本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.