我正在尝试在两个单独的 docker 容器中运行 spring boot 应用程序(作为简单的 REST api)和 mysql 服务器。但是,我无法在 Spring 应用程序中获取 jdbc 连接来连接 mysql。它们都是独立工作的,当我在本地运行 spring boot 和 mysql 时,实现就可以工作。
docker-compose.yml
version: '3'
services:
database:
image: mysql:latest
container_name: mysqldb
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
- MYSQL_ROOT_PASSWORD=password
expose:
- 3306
ports:
- 3306:3306
networks:
- backend
volumes:
- "dbdata:/var/lib/mysql"
web:
container_name: springboot
build: .
depends_on:
- database
expose:
- 8080
ports:
- 8080:8080
networks:
- backend
networks:
backend:
volumes:
dbdata:
在 Spring Boot 应用程序中:
val dataSource = DriverManagerDataSource()
dataSource.setDriverClassName("com.mysql.jdbc.Driver")
dataSource.setUrl("jdbc:mysql://mysqldb:3306/$dbName?characterEncoding=latin1")
dataSource.username = "dev"
dataSource.password = "password"
val jdbcTemplate = JdbcTemplate(dataSource)
从 Spring Boot 返回错误:
{
"status": 500,
"error": "Internal Server Error",
"message": "Failed to obtain JDBC Connection; nested exception is com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure\n\nThe last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server."
}
我能够通过 mysql cli 从 spring boot 容器连接到 mysql 容器。所以,看来 springboot 容器能够解析“mysqldb”。
这看起来应该很简单。我不确定错误出在哪里,但我猜这与我不熟悉的 Spring Boots 内部工作原理有关。
最佳答案
将此 dataSource.setUrl("jdbc:mysql://mysqldb:3306/$dbName")
更改为:
dataSource.setUrl("jdbc:mysql://database:3306/$dbName")
您在compose
中的服务名称是database
,因此您需要使用它
关于mysql - Spring boot JDBC无法连接docker容器中的mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58162333/