I’m trying out a few new things right now, and I wanted to create a small Spring/mySQL application. I’ve set up a docker-compose file as the following:
version: '3.3'
services:
docker-mysql:
container_name: docker-mysql
image: mysql:5.7
restart: always
environment:
- MYSQL_ROOT_PASSWORD=root
volumes:
- db_data:/var/lib/mysql
- ./initalize.sql:/docker-entrypoint-initdb.d/initalize.sql:ro
ports:
- 3306:3306
expose:
- 3306
volumes:
db_data: {}
In the initalize.sql I set up a base TEST database with a few test tables and fill a few of them up, it works fine, I could query elements via command line.
On the other hand I cannot connect to it via Spring, I have the following application.properties file:
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.datasource.url=jdbc:mysql://localhost:3306/TEST?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Every time I try to launch the app it gets (I’m not running the app in a docker image, it’s running on Windows) a com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure error, and it can’t find the server.
I also tried to connect to change the datasource url to jdbc:mysql://docker-mysql:3306/TEST?useSSL=false but it didn’t work either.
2
Answers
If you want this works:
Your Spring Boot app should be running as a docker container on the same virtual network as your MySQL docker container or both containers should be running on the default bridge network provided by docker.
What you intend to do will only work if you allow access to your host:port to be routed to the mariadb container. You’d not only have to expose the port but also to place it on the host network. See https://docs.docker.com/network/drivers/host/
Note that in this setup you still won’t be able to access localhost:port but hostname:port.
The other possibility is to place your client application into another docker container on the same network. See https://docs.docker.com/network/