Spring Docker Container 停止,因为它尝试连接到 localhost MongoDB,即使它已经正确连接到 MongoDB Container
Posted
技术标签:
【中文标题】Spring Docker Container 停止,因为它尝试连接到 localhost MongoDB,即使它已经正确连接到 MongoDB Container【英文标题】:Spring Docker Container stops because it tries to connect to localhost MongoDB even though it already connects correctly to MongoDB Container 【发布时间】:2020-05-23 18:18:45 【问题描述】:编辑:解决方案如 Valijon 所述。但此外,在我第一次插入 DemoApplication.java 之前,缺少以下行:
MongoOperations mongoOps = new MongoTemplate(new SimpleMongoClientDbFactory(new ConnectionString("mongodb://docker_mongo:27017/db")));
所以我编写了一个非常基本的 Spring 应用程序,它应该连接到 MongoDB、存储一些数据、检索它并打印一些用于测试目的的东西。
为此,我使用docker-compose up
创建了一个容器“docker_mongo”和一个名为“docker_spring”的容器。
现在与 Mongo 容器的连接实际上是成功的(请参阅日志),但之后,Spring 容器会尝试在 localhost:27017 上建立与标准 MongoDB 的另一个连接。然后失败,导致容器以代码 1 退出。
我还编辑了我的application.properties
(见下文)。
我猜它与 Spring Mongo 自动配置有关,我已经尝试按照这篇文章中的描述停用它:Mongo tries to connect automatically to port 27017(localhost)。
但是,停用自动配置会导致其他错误,我现在不知道如何解决(我想我必须重构我在 Spring 应用程序中连接到 MongoDB 的方式,并且我没有找到足够简单的教程互联网告诉我如何在不使用自动配置功能的情况下做到这一点)。
在编码方面我真的是一个初学者,如果问题质量低劣或重复
我觉得解决方案真的很简单,但是我没有找到完全涵盖我的问题的文章:'(
application.properties:
spring.data.mongodb.host=mongo
spring.data.mongodb.port=27017
spring.data.mongodb.database=db
spring.data.mongodb.uri=mongodb://docker_mongo:27017/db
Dockerfile:
FROM openjdk:11
VOLUME /tmp
ARG JAR_FILE=target/*.jar
COPY $JAR_FILE /tmp/app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/tmp/app.jar"]
RUN echo "hello world"
docker-compose.yaml:
version: '3.1'
services:
mongo:
container_name: docker_mongo
networks:
- gateway
ports:
- "27017:27017"
hostname: mongo
image: mongo:latest
command: mongod --port 27017
volumes:
- ./data/db:/data/db
spring:
build: .
container_name: docker_spring
networks:
- gateway
ports:
- "8080:8080"
hostname: spring
depends_on:
- mongo
networks:
gateway:
driver: "bridge"
由 main 调用的 DemoApplication.java(我将其外包到一个单独的类中):
package com.example.demo;
import com.example.model.Expenditure;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import java.time.LocalDate;
/*
@SpringBootApplication(exclude=
MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class
)
*/
@SpringBootApplication
@ComponentScan("com.example.client","com.example.demo","com.example.model")
public class DemoApplication implements CommandLineRunner
@Autowired
private ExpenditureRepository repository;
@Override
public void run(String... args) throws Exception
MongoOperations mongoOps = new MongoTemplate(new SimpleMongoClientDbFactory(MongoClients.create(), "db"));
mongoOps.insert(new Expenditure("Aldi",10.01, LocalDate.parse("2019-10-05")));
System.out.println(mongoOps.findOne(new Query(Criteria.where("name").is("Aldi")),Expenditure.class));
mongoOps.dropCollection("expenditure");
PopulateExpenditureDB.populateExpenditures(mongoOps);
MongoDbFactory.java:
package com.example.demo;
import com.mongodb.client.MongoDatabase;
import org.springframework.dao.DataAccessException;
public interface MongoDbFactory
MongoDatabase getDb() throws DataAccessException;
MongoDatabase getDb(String dbName) throws DataAccessException;
ExpenditureRepository.java:
package com.example.demo;
import com.example.model.Expenditure;
import java.time.LocalDate;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
//mongodb Host & Port defined in application.properties
public interface ExpenditureRepository extends MongoRepository<Expenditure, String>
/*
public void create(Expenditure expenditure)
if(expenditure.)
public Expenditure findById(int id)
return data.get(id)
*/
public Expenditure findByName (String name);
public List<Expenditure> findByExDate (LocalDate exDate);
Docker 日志:
~/new_Webapp$ sudo docker-compose up
Creating network "newwebapp_gateway" with driver "bridge"
Building spring
Step 1/6 : FROM openjdk:11
---> 612d4d483eee
Step 2/6 : VOLUME /tmp
---> Running in 3aff2f893162
Removing intermediate container 3aff2f893162
---> 2bf19d4c67b1
Step 3/6 : ARG JAR_FILE=target/*.jar
---> Running in b7c3782bbc1a
Removing intermediate container b7c3782bbc1a
---> b029607db12b
Step 4/6 : COPY $JAR_FILE /tmp/app.jar
---> f3168bc17ae3
Step 5/6 : ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/tmp/app.jar"]
---> Running in f729f7204cdd
Removing intermediate container f729f7204cdd
---> aceb4c1a0bda
Step 6/6 : RUN echo "hello world"
---> Running in d4ab9bb0f498
hello world
Removing intermediate container d4ab9bb0f498
---> 45ae63ef2bd1
Successfully built 45ae63ef2bd1
Successfully tagged newwebapp_spring:latest
WARNING: Image for service spring was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Creating docker_mongo ...
Creating docker_mongo ... done
Creating docker_spring ...
Creating docker_spring ... done
Attaching to docker_mongo, docker_spring
docker_mongo | 2020-02-07T14:45:26.462+0000 I CONTROL [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
docker_mongo | 2020-02-07T14:45:26.464+0000 I CONTROL [initandlisten] MongoDB starting : pid=1 port=27017 dbpath=/data/db 64-bit host=mongo
docker_mongo | 2020-02-07T14:45:26.464+0000 I CONTROL [initandlisten] db version v4.2.2
docker_mongo | 2020-02-07T14:45:26.464+0000 I CONTROL [initandlisten] git version: a0bbbff6ada159e19298d37946ac8dc4b497eadf
docker_mongo | 2020-02-07T14:45:26.464+0000 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.1.1 11 Sep 2018
docker_mongo | 2020-02-07T14:45:26.464+0000 I CONTROL [initandlisten] allocator: tcmalloc
docker_mongo | 2020-02-07T14:45:26.464+0000 I CONTROL [initandlisten] modules: none
docker_mongo | 2020-02-07T14:45:26.464+0000 I CONTROL [initandlisten] build environment:
docker_mongo | 2020-02-07T14:45:26.464+0000 I CONTROL [initandlisten] distmod: ubuntu1804
docker_mongo | 2020-02-07T14:45:26.464+0000 I CONTROL [initandlisten] distarch: x86_64
docker_mongo | 2020-02-07T14:45:26.464+0000 I CONTROL [initandlisten] target_arch: x86_64
docker_mongo | 2020-02-07T14:45:26.464+0000 I CONTROL [initandlisten] options: net: bindIp: "*", port: 27017
docker_mongo | 2020-02-07T14:45:26.464+0000 I STORAGE [initandlisten] Detected data files in /data/db created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
docker_mongo | 2020-02-07T14:45:26.464+0000 I STORAGE [initandlisten]
docker_mongo | 2020-02-07T14:45:26.464+0000 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
docker_mongo | 2020-02-07T14:45:26.464+0000 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem
docker_mongo | 2020-02-07T14:45:26.464+0000 I STORAGE [initandlisten] wiredtiger_open config: create,cache_size=7471M,cache_overflow=(file_max=0M),session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000,close_scan_interval=10,close_handle_minimum=250),statistics_log=(wait=0),verbose=[recovery_progress,checkpoint_progress],
docker_mongo | 2020-02-07T14:45:26.877+0000 I STORAGE [initandlisten] WiredTiger message [1581086726:877548][1:0x7ff0c5201b00], txn-recover: Recovering log 36 through 37
docker_mongo | 2020-02-07T14:45:26.904+0000 I STORAGE [initandlisten] WiredTiger message [1581086726:904522][1:0x7ff0c5201b00], txn-recover: Recovering log 37 through 37
docker_mongo | 2020-02-07T14:45:26.950+0000 I STORAGE [initandlisten] WiredTiger message [1581086726:950147][1:0x7ff0c5201b00], txn-recover: Main recovery loop: starting at 36/5888 to 37/256
docker_mongo | 2020-02-07T14:45:27.008+0000 I STORAGE [initandlisten] WiredTiger message [1581086727:8723][1:0x7ff0c5201b00], txn-recover: Recovering log 36 through 37
docker_mongo | 2020-02-07T14:45:27.044+0000 I STORAGE [initandlisten] WiredTiger message [1581086727:44798][1:0x7ff0c5201b00], txn-recover: Recovering log 37 through 37
docker_mongo | 2020-02-07T14:45:27.075+0000 I STORAGE [initandlisten] WiredTiger message [1581086727:75209][1:0x7ff0c5201b00], txn-recover: Set global recovery timestamp: (0,0)
docker_mongo | 2020-02-07T14:45:27.102+0000 I RECOVERY [initandlisten] WiredTiger recoveryTimestamp. Ts: Timestamp(0, 0)
docker_mongo | 2020-02-07T14:45:27.106+0000 I STORAGE [initandlisten] Timestamp monitor starting
docker_mongo | 2020-02-07T14:45:27.109+0000 I CONTROL [initandlisten]
docker_mongo | 2020-02-07T14:45:27.110+0000 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
docker_mongo | 2020-02-07T14:45:27.110+0000 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
docker_mongo | 2020-02-07T14:45:27.110+0000 I CONTROL [initandlisten]
docker_mongo | 2020-02-07T14:45:27.112+0000 I SHARDING [initandlisten] Marking collection local.system.replset as collection version: <unsharded>
docker_mongo | 2020-02-07T14:45:27.114+0000 I STORAGE [initandlisten] Flow Control is enabled on this deployment.
docker_mongo | 2020-02-07T14:45:27.114+0000 I SHARDING [initandlisten] Marking collection admin.system.roles as collection version: <unsharded>
docker_mongo | 2020-02-07T14:45:27.114+0000 I SHARDING [initandlisten] Marking collection admin.system.version as collection version: <unsharded>
docker_mongo | 2020-02-07T14:45:27.116+0000 I SHARDING [initandlisten] Marking collection local.startup_log as collection version: <unsharded>
docker_mongo | 2020-02-07T14:45:27.116+0000 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'
docker_mongo | 2020-02-07T14:45:27.118+0000 I SHARDING [LogicalSessionCacheRefresh] Marking collection config.system.sessions as collection version: <unsharded>
docker_mongo | 2020-02-07T14:45:27.118+0000 I NETWORK [initandlisten] Listening on /tmp/mongodb-27017.sock
docker_mongo | 2020-02-07T14:45:27.118+0000 I NETWORK [initandlisten] Listening on 0.0.0.0
docker_mongo | 2020-02-07T14:45:27.118+0000 I SHARDING [LogicalSessionCacheReap] Marking collection config.transactions as collection version: <unsharded>
docker_mongo | 2020-02-07T14:45:27.118+0000 I NETWORK [initandlisten] waiting for connections on port 27017
docker_spring |
docker_spring | . ____ _ __ _ _
docker_spring | /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
docker_spring | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
docker_spring | \\/ ___)| |_)| | | | | || (_| | ) ) ) )
docker_spring | ' |____| .__|_| |_|_| |_\__, | / / / /
docker_spring | =========|_|==============|___/=/_/_/_/
docker_spring | :: Spring Boot :: (v2.2.1.RELEASE)
docker_spring |
docker_spring | 2020-02-07 14:45:27.552 INFO 1 --- [ main] com.example.demo.MainClass : Starting MainClass v0.0.1-SNAPSHOT on spring with PID 1 (/tmp/app.jar started by root in /)
docker_spring | 2020-02-07 14:45:27.556 INFO 1 --- [ main] com.example.demo.MainClass : No active profile set, falling back to default profiles: default
docker_spring | 2020-02-07 14:45:27.950 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
docker_spring | 2020-02-07 14:45:27.992 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 38ms. Found 1 repository interfaces.
docker_mongo | 2020-02-07T14:45:28.000+0000 I SHARDING [ftdc] Marking collection local.oplog.rs as collection version: <unsharded>
docker_spring | 2020-02-07 14:45:28.364 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
docker_spring | 2020-02-07 14:45:28.372 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
docker_spring | 2020-02-07 14:45:28.372 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.27]
docker_spring | 2020-02-07 14:45:28.425 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
docker_spring | 2020-02-07 14:45:28.426 INFO 1 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 822 ms
docker_spring | 2020-02-07 14:45:28.616 INFO 1 --- [ main] org.mongodb.driver.cluster : Cluster created with settings hosts=[docker_mongo:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500
docker_mongo | 2020-02-07T14:45:28.643+0000 I NETWORK [listener] connection accepted from 192.168.0.3:53260 #1 (1 connection now open)
docker_mongo | 2020-02-07T14:45:28.649+0000 I NETWORK [conn1] received client metadata from 192.168.0.3:53260 conn1: driver: name: "mongo-java-driver|legacy", version: "3.11.2" , os: type: "Linux", name: "Linux", architecture: "amd64", version: "5.3.0-28-generic" , platform: "Java/Oracle Corporation/11.0.6+10"
docker_spring | 2020-02-07 14:45:28.659 INFO 1 --- [ker_mongo:27017] org.mongodb.driver.connection : Opened connection [connectionIdlocalValue:1, serverValue:1] to docker_mongo:27017
docker_spring | 2020-02-07 14:45:28.663 INFO 1 --- [ker_mongo:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescriptionaddress=docker_mongo:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersionversionList=[4, 2, 2], minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=2669943
docker_spring | 2020-02-07 14:45:28.703 WARN 1 --- [ main] o.s.data.convert.CustomConversions : Registering converter from class java.time.LocalDateTime to class java.time.Instant as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.
docker_spring | 2020-02-07 14:45:28.703 WARN 1 --- [ main] o.s.data.convert.CustomConversions : Registering converter from class java.time.Instant to class java.time.LocalDateTime as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.
docker_spring | 2020-02-07 14:45:28.717 WARN 1 --- [ main] o.s.data.convert.CustomConversions : Registering converter from class java.time.LocalDateTime to class java.time.Instant as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.
docker_spring | 2020-02-07 14:45:28.717 WARN 1 --- [ main] o.s.data.convert.CustomConversions : Registering converter from class java.time.Instant to class java.time.LocalDateTime as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.
docker_spring | 2020-02-07 14:45:28.951 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
docker_spring | 2020-02-07 14:45:29.076 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
docker_spring | 2020-02-07 14:45:29.078 INFO 1 --- [ main] com.example.demo.MainClass : Started MainClass in 1.787 seconds (JVM running for 2.142)
docker_spring | 2020-02-07 14:45:29.081 INFO 1 --- [ main] org.mongodb.driver.cluster : Cluster created with settings hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500
docker_spring | 2020-02-07 14:45:29.083 WARN 1 --- [ main] o.s.data.convert.CustomConversions : Registering converter from class java.time.LocalDateTime to class java.time.Instant as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.
docker_spring | 2020-02-07 14:45:29.083 WARN 1 --- [ main] o.s.data.convert.CustomConversions : Registering converter from class java.time.Instant to class java.time.LocalDateTime as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.
docker_spring | 2020-02-07 14:45:29.085 WARN 1 --- [ main] o.s.data.convert.CustomConversions : Registering converter from class java.time.LocalDateTime to class java.time.Instant as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.
docker_spring | 2020-02-07 14:45:29.085 WARN 1 --- [ main] o.s.data.convert.CustomConversions : Registering converter from class java.time.Instant to class java.time.LocalDateTime as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.
docker_spring | 2020-02-07 14:45:29.086 INFO 1 --- [localhost:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server localhost:27017
docker_spring |
docker_spring | com.mongodb.MongoSocketOpenException: Exception opening socket
docker_spring | at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-3.11.2.jar!/:na]
docker_spring | at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:128) ~[mongodb-driver-core-3.11.2.jar!/:na]
docker_spring | at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117) ~[mongodb-driver-core-3.11.2.jar!/:na]
docker_spring | at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
docker_spring | Caused by: java.net.ConnectException: Connection refused (Connection refused)
docker_spring | at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na]
docker_spring | at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399) ~[na:na]
docker_spring | at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242) ~[na:na]
docker_spring | at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224) ~[na:na]
docker_spring | at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403) ~[na:na]
docker_spring | at java.base/java.net.Socket.connect(Socket.java:609) ~[na:na]
docker_spring | at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:64) ~[mongodb-driver-core-3.11.2.jar!/:na]
docker_spring | at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-3.11.2.jar!/:na]
docker_spring | at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-3.11.2.jar!/:na]
docker_spring | ... 3 common frames omitted
docker_spring |
docker_spring | 2020-02-07 14:45:29.119 INFO 1 --- [ main] org.mongodb.driver.cluster : Cluster description not yet available. Waiting for 30000 ms before timing out
docker_spring | 2020-02-07 14:45:59.125 INFO 1 --- [ main] ConditionEvaluationReportLoggingListener :
docker_spring |
docker_spring | Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
docker_spring | 2020-02-07 14:45:59.131 ERROR 1 --- [ main] o.s.boot.SpringApplication : Application run failed
docker_spring |
docker_spring | java.lang.IllegalStateException: Failed to execute CommandLineRunner
docker_spring | at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:787) ~[spring-boot-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:768) ~[spring-boot-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) ~[spring-boot-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) ~[spring-boot-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at com.example.demo.MainClass.main(MainClass.java:8) ~[classes!/:0.0.1-SNAPSHOT]
docker_spring | at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
docker_spring | at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
docker_spring | at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
docker_spring | at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
docker_spring | at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) ~[app.jar:0.0.1-SNAPSHOT]
docker_spring | at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) ~[app.jar:0.0.1-SNAPSHOT]
docker_spring | at org.springframework.boot.loader.Launcher.launch(Launcher.java:51) ~[app.jar:0.0.1-SNAPSHOT]
docker_spring | at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:52) ~[app.jar:0.0.1-SNAPSHOT]
docker_spring | Caused by: org.springframework.dao.DataAccessResourceFailureException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is type=UNKNOWN, servers=[address=localhost: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=localhost:27017, type=UNKNOWN, state=CONNECTING, exception=com.mongodb.MongoSocketOpenException: Exception opening socket, caused by java.net.ConnectException: Connection refused (Connection refused)]
docker_spring | at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:90) ~[spring-data-mongodb-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2902) ~[spring-data-mongodb-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:587) ~[spring-data-mongodb-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at org.springframework.data.mongodb.core.MongoTemplate.insertDocument(MongoTemplate.java:1494) ~[spring-data-mongodb-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at org.springframework.data.mongodb.core.MongoTemplate.doInsert(MongoTemplate.java:1294) ~[spring-data-mongodb-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at org.springframework.data.mongodb.core.MongoTemplate.insert(MongoTemplate.java:1226) ~[spring-data-mongodb-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at org.springframework.data.mongodb.core.MongoTemplate.insert(MongoTemplate.java:1211) ~[spring-data-mongodb-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at com.example.demo.DemoApplication.run(DemoApplication.java:40) ~[classes!/:0.0.1-SNAPSHOT]
docker_spring | at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:784) ~[spring-boot-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | ... 13 common frames omitted
docker_spring | Caused by: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is type=UNKNOWN, servers=[address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception=com.mongodb.MongoSocketOpenException: Exception opening socket, caused by java.net.ConnectException: Connection refused (Connection refused)]
docker_spring | at com.mongodb.internal.connection.BaseCluster.getDescription(BaseCluster.java:182) ~[mongodb-driver-core-3.11.2.jar!/:na]
docker_spring | at com.mongodb.internal.connection.SingleServerCluster.getDescription(SingleServerCluster.java:41) ~[mongodb-driver-core-3.11.2.jar!/:na]
docker_spring | at com.mongodb.client.internal.MongoClientDelegate.getConnectedClusterDescription(MongoClientDelegate.java:145) ~[mongodb-driver-3.11.2.jar!/:na]
docker_spring | at com.mongodb.client.internal.MongoClientDelegate.createClientSession(MongoClientDelegate.java:100) ~[mongodb-driver-3.11.2.jar!/:na]
docker_spring | at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.getClientSession(MongoClientDelegate.java:277) ~[mongodb-driver-3.11.2.jar!/:na]
docker_spring | at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:201) ~[mongodb-driver-3.11.2.jar!/:na]
docker_spring | at com.mongodb.client.internal.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:1048) ~[mongodb-driver-3.11.2.jar!/:na]
docker_spring | at com.mongodb.client.internal.MongoCollectionImpl.executeInsertOne(MongoCollectionImpl.java:498) ~[mongodb-driver-3.11.2.jar!/:na]
docker_spring | at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:482) ~[mongodb-driver-3.11.2.jar!/:na]
docker_spring | at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:476) ~[mongodb-driver-3.11.2.jar!/:na]
docker_spring | at org.springframework.data.mongodb.core.MongoTemplate.lambda$insertDocument$16(MongoTemplate.java:1500) ~[spring-data-mongodb-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:585) ~[spring-data-mongodb-2.2.1.RELEASE.jar!/:2.2.1.RELEASE]
docker_spring | ... 19 common frames omitted
docker_spring |
docker_spring | 2020-02-07 14:45:59.140 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
docker_mongo | 2020-02-07T14:45:59.146+0000 I NETWORK [conn1] end connection 192.168.0.3:53260 (0 connections now open)
docker_spring exited with code 1
【问题讨论】:
【参考方案1】:很简单
MongoClients.create()
不带任何参数连接到在 localhost 的 27017 端口上运行的 MongoDB 实例。
https://mongodb.github.io/mongo-java-driver/3.4/driver-async/tutorials/connect-to-mongodb/#connect-to-a-standalone-mongodb-instance
Spring Boot 已经连接到 MongoDB
docker_spring | 2020-02-07 14:45:28.616 INFO 1 --- [ main] org.mongodb.driver.cluster : Cluster created with settings hosts=[docker_mongo:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500
docker_mongo | 2020-02-07T14:45:28.643+0000 I NETWORK [listener] connection accepted from 192.168.0.3:53260 #1 (1 connection now open)
docker_mongo | 2020-02-07T14:45:28.649+0000 I NETWORK [conn1] received client metadata from 192.168.0.3:53260 conn1: driver: name: "mongo-java-driver|legacy", version: "3.11.2" , os: type: "Linux", name: "Linux", architecture: "amd64", version: "5.3.0-28-generic" , platform: "Java/Oracle Corporation/11.0.6+10"
docker_spring | 2020-02-07 14:45:28.659 INFO 1 --- [ker_mongo:27017] org.mongodb.driver.connection : Opened connection [connectionIdlocalValue:1, serverValue:1] to docker_mongo:27017
docker_spring | 2020-02-07 14:45:28.663 INFO 1 --- [ker_mongo:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescriptionaddress=docker_mongo:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersionversionList=[4, 2, 2], minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=2669943
改成这样:
@SpringBootApplication
@ComponentScan("com.example.client","com.example.demo","com.example.model")
public class DemoApplication implements CommandLineRunner
@Autowired
private MongoOperations mongoOps;
@Override
public void run(String... args) throws Exception
mongoOps.insert(new Expenditure("Aldi",10.01, LocalDate.parse("2019-10-05")));
System.out.println(mongoOps.findOne(new Query(Criteria.where("name").is("Aldi")),Expenditure.class));
mongoOps.dropCollection("expenditure");
PopulateExpenditureDB.populateExpenditures(mongoOps);
【讨论】:
非常感谢!这正是问题所在:) 但是我需要做的与您的代码不同的一件事是在我第一次插入之前插入以下行: MongoOperations mongoOps = new MongoTemplate(new SimpleMongoClientDbFactory(new ConnectionString("mongodb://docker_mongo: 27017/db")));否则不会设置 mongoOps。 @Dannnn 没必要。@Autowired private MongoOperations mongoOps
已经从 Spring 上下文中获得了单例。试试看以上是关于Spring Docker Container 停止,因为它尝试连接到 localhost MongoDB,即使它已经正确连接到 MongoDB Container的主要内容,如果未能解决你的问题,请参考以下文章
Docker(Spring Boot 或 Thorntail)和 Keycloak
Docker Gitlab CI 部署 Spring Boot 项目