Springboot mongo docker-compose 连接失败

Posted

技术标签:

【中文标题】Springboot mongo docker-compose 连接失败【英文标题】:Springboot mongo docker-compose fail to connect 【发布时间】:2019-12-07 08:56:42 【问题描述】:

我的docker-compose.yml如图

version: '3'
services:
  backend-service:
    image: 'storio-360-service:v1.0'
    build: .
    container_name: storio-360-service
    ports:
      - 8090:8080
    depends_on:
      - db_mongo
    links:
      - db_mongo
  db_mongo:
    image: 'mongo'
    container_name: db_mongo
    ports:
      - 27018:27017
    volumes:
      - /home/bob/Bob/data:/data/db
    restart: always

我的 Dockerfile 是

FROM openjdk:8u111-jdk-alpine
VOLUME /tmp
ADD /target/backend-service-1.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
CMD curl "db_mongo:27018"

由于这个设置,我春天的存储库有这个代码

@Repository
public class WatcherRepository 

    private MongoOperations mongoOps;

    @Autowired
    public WatcherRepository() 
        String myHost = "db_mongo";
        this.mongoOps = new MongoTemplate(new SimpleMongoDbFactory(new MongoClient(myHost), MongoConstant.DATABASE_NAME));
    

    // Other code to access the mongo db

但是,当我运行 docker-compose up --build 时,

当 Spring boot 启动时,我得到以下信息,

02:24:55.871 [main] INFO  org.mongodb.driver.cluster - Cluster created with settings hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500
storio-360-service    | 02:24:55.923 [cluster-ClusterIdvalue='5d3faa779470450001317225', description='null'-localhost:27017] INFO  org.mongodb.driver.cluster - Exception in monitor thread while connecting to server localhost:27017
storio-360-service    | com.mongodb.MongoSocketOpenException: Exception opening socket
storio-360-service    |         at com.mongodb.connection.SocketStream.open(SocketStream.java:62)
storio-360-service    |         at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126)
storio-360-service    |         at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114)
storio-360-service    |         at java.lang.Thread.run(Thread.java:745)
storio-360-service    | Caused by: java.net.ConnectException: Connection refused (Connection refused)
storio-360-service    |         at java.net.PlainSocketImpl.socketConnect(Native Method)
storio-360-service    |         at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
storio-360-service    |         at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
storio-360-service    |         at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
storio-360-service    |         at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
storio-360-service    |         at java.net.Socket.connect(Socket.java:589)
storio-360-service    |         at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:59)
storio-360-service    |         at com.mongodb.connection.SocketStream.open(SocketStream.java:57)
storio-360-service    |         ... 3 common frames omitted
storio-360-service    | 02:24:56.060 [main] INFO  org.mongodb.driver.cluster - Cluster created with settings hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500

然后Spring boot会显示它正在等待调用,因为它设置成功。

02:34:39.274 [main] INFO  o.d.i.i.storio.service.Service - Started Service in 5.353 seconds (JVM running for 6.085)

但是,当我进行将调用 mongodb 的 api 调用时,它会显示错误

Timed out after 30000 ms while waiting to connect. Client view of cluster state is type=UNKNOWN, servers=[address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception=com.mongodb.MongoSocketOpenException: Exception opening socket, caused by java.net.ConnectException: Connection refused (Connection refused)]; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is type=UNKNOWN, servers=[address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception=com.mongodb.MongoSocketOpenException: Exception opening socket, caused by java.net.ConnectException: Connection refused (Connection refused)]

我是 Docker 新手,很明显我的 springboot 无法访问 mongo。我在 Dockerfile 或 docker-compose 中做错了什么?谢谢

【问题讨论】:

【参考方案1】:

看起来您正在将 mongodb 端口转发到 27018

   - 27018:27017

并且您没有在 Spring 配置中指定 27018

因此 Spring boot 默认会尝试连接到27017

解决方案: 删除端口转发,或更新 Spring Boot 配置以使用 mongo 27018


更新:

这里有一些 Spring Boot 的 OP 的 mongo 自动配置技巧。

依赖于一个 mongodb 启动器来进行 Spring Boot

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-mongodb -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
    <version>2.1.6.RELEASE</version>
</dependency>

在应用程序属性中提供 Mongo DB 详细信息。

spring.data.mongodb.database= # Database name.
spring.data.mongodb.host= # Mongo server host. Cannot be set with URI.
spring.data.mongodb.password= # Login password of the mongo server. Cannot be set with URI.
spring.data.mongodb.port= # Mongo server port. Cannot be set with URI.
spring.data.mongodb.username= # Login user of the mongo server. Cannot be set with URI

(这里OP需要指定他的mongodb主机和端口)

现在,唯一剩下的就是自动连接MongoTemplate,无论您想在哪里使用。

@Autowired
private MongoTemplate mongoTemplate;

【讨论】:

您好,我尝试在 Repository 类中进行更改。字符串 myHost = "db_mongo:27018"; this.mongoOps = new MongoTemplate(new SimpleMongoDbFactory(new MongoClient(myHost), MongoConstant.SG_FEEDS));但是,它仍然无法正常工作。如何正确将端口从 27017 更改为 27018 在你的 application.properties 添加spring.data.mongodb.port= 27018 看起来你和 Spring Boot 有冲突。使用spring boot,您不需要自己创建MongoTemplate,SB会根据属性文件中提供的DB详细信息为您完成 mongotemplate 允许我以原生方式查询 mongo。它适用于开发。我可以在代码或 docker compose 中指定端口差异的方式吗? @Desmond 对于我的回答,我尝试简单介绍一下 Spring Boot 如何自动创建 MongoTemplate。希望对你有帮助

以上是关于Springboot mongo docker-compose 连接失败的主要内容,如果未能解决你的问题,请参考以下文章

springboot整合mongo多数据源

springboot~mongo内嵌集合的操作

springboot集成mongo

Springboot mongo异常与Docker

[记录] springboot-mongo 去除_class 字段

SpringBoot操作mongo的两种方法