I'm trying to run a spring boot app (as a simple REST api) and mysql server in two separate docker containers. But, I can't get the jdbc connection in the spring app to connect to mysql. They are both working independently and the implementation works when I run spring boot and mysql locally.
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:
In the spring boot app:
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)
Error returned from 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."
}
I AM able to connect to the mysql container from the spring boot container via the mysql cli. So, it appears the springboot container is able to resolve "mysqldb."
This seems like it should be pretty simple. I'm not sure where the error lies but I would guess it has something to do with spring boots inner workings that I am unfamiliar with.
change this dataSource.setUrl("jdbc:mysql://mysqldb:3306/$dbName")
, to:
dataSource.setUrl("jdbc:mysql://database:3306/$dbName")
your service name in compose
is database
, so you need to use it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.