猿问

使用Docker桥接网络时无法在集成测试中获取JDBC连接

当我在maven test本地运行时通过。但是,当我在CI服务器上运行该错误时,出现此错误。


Error Message

Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection

Stacktrace

org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection

Caused by: org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection

Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: 

Communications link failure


The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

Caused by: java.net.UnknownHostException: mysql

运行本地测试时,它们都通过了测试,并使用IntelliJ IDEA提供的maven测试默认设置。

由于该错误抱怨数据库连接问题,因此我通过Jenkins Audit检查了Database Plugin。连接成功!

我的连接参数application.properties也与此对应


spring.datasource.url=jdbc:mysql://mysql:3306/database?useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai

spring.datasource.username=root

spring.datasource.password=password

spring.datasource.maxActive=5

URL中的MySQL是MySQL docker容器名称。如果用错误消息中的localhost或专用IP进行更改docker container inspect mysql是相同的,而后两行中的Stacktrace则有所不同。


对于本地主机


The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

Caused by: java.net.ConnectException: Connection refused (Connection refused)

用于私有IP


The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. 

Caused by: java.net.SocketTimeoutException: connect timed out

我认为不同的是URL中的主机,localhost用于本地测试。而Jenkins服务器则使用Docker桥接网络。


总结:
1.通过maven的本地测试通过
2. Jenkins插件成功连接到MySQL
3.从Jenkins运行时,集成测试失败
。4.本地测试环境为WIN10 64bit;Jenkins在Ubuntu 16.04 64位服务器上的docker容器中运行,MySQL 5.7容器连接到同一网桥网络。


守候你守候我
浏览 535回答 3
3回答

牧羊人nacy

您应该将Docker容器的mysql端口绑定到VM中的端口。在下面的线程中对此进行了很好的解释。值得尝试...如何与在Docker中作为容器运行的MySQL DB连接?
随时随地看视频慕课网APP

相关分类

Java
我要回答