[英]Getting “Exception opening socket” on Mongodb connection from Spring App (docker-compose)
Even though I'm giving in the application properties,即使我在应用程序属性中给出,
spring.data.mongodb.host=api-database4
as the hostname which is the container name and hostname of the MongoDB on the docker-compose file, Spring app still can't connect to the MongoDB instance.作为docker-compose文件中MongoDB的容器名和主机名的主机名,Spring应用程序仍然无法连接到MongoDB实例。 I can however connect from MongoDB Compass to localhost:27030 but not to mongodb://api-database4:27030/messagingServiceDb .
但是,我可以从 MongoDB Compass 连接到localhost:27030但不能连接到mongodb://api-database4:27030/messagingServiceDb 。
My docker-compose file;我的 docker-compose 文件;
version: '3'
services:
messaging-api6:
container_name: 'messaging-api6'
build: ./messaging-api
restart: always
ports:
- 8085:8080
depends_on:
- api-database4
networks:
- shared-net
api-database4:
image: mongo
container_name: api-database4
hostname: api-database4
restart: always
ports:
- 27030:27017
networks:
- shared-net
command: mongod --bind_ip_all
networks:
shared-net:
driver: bridge
and my Docker file for the Spring app is;我的 Spring 应用程序的 Docker 文件是;
FROM openjdk:12-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
and my application.properties are;我的 application.properties 是;
#Local MongoDB config
spring.data.mongodb.database=messagingServiceDb
spring.data.mongodb.port=27030
spring.data.mongodb.host=api-database4
Entire code can be seen here .整个代码可以在这里看到。
How can I make my spring app on a docker container create a connection to the MongoDB instance which is on another docker container?如何让我的 docker 容器上的 spring 应用程序创建到另一个 docker 容器上的 MongoDB 实例的连接?
I have tried the solutions on similar questions and replicated them, it still gives the same error.我已经尝试过类似问题的解决方案并复制它们,它仍然给出相同的错误。
Edit and Solution:编辑和解决方案:
I solved the issue by commenting out configuration below,我通过注释掉下面的配置解决了这个问题,
#Local MongoDB config
#spring.data.mongodb.database=messagingServiceDb
spring.data.mongodb.host=api-database4
spring.data.mongodb.port=27030
The remaining question is, why?剩下的问题是,为什么? That was the correct port that I'm trying to connect.
那是我尝试连接的正确端口。 Could it be related to the configuration order?
会不会跟配置顺序有关?
ports
directive in docker-compose
publishes container ports to the host machine. docker-compose
ports
指令将容器端口发布到主机。 The containers communicate with each other on exposed ports.容器在暴露的端口上相互通信。 You can test whether a container can reach another with netcat.
您可以使用 netcat 测试一个容器是否可以访问另一个容器。
docker exec -it messaging-api6 bash
> apt-get install netcat
> nc -z -v api-database4 27030
> nc -z -v api-database4 27017
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.