I am trying to run a Spring Boot application where db has to be connected to a MySQL container on Docker. I used following code and commands.
Application properties:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://mysqldb:3306/practice
spring.datasource.username=root
spring.datasource.password=CVnit1234!
spring.jpa.show-sql=true
spring.sql.init.platform=mysql
spring.sql.init.mode=always
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=update
Commands used for creating container & running it on Docker:
Pulling mysql image from Docker Hub:
docker pull mysql
Creating a container:
docker run --name mysqldb --network spring-net -p 3307:3306 -e MYSQL_ROOT_PASSWORD=password MYSQL_DATABASE=practice -d mysql:latest
After this command, a container is created and even it is up and working fine. I was able to login to sql bash and execute some queries.
I tried with multiple jdbc urls:
- jdbc:mysql://mysqldb:3306/practice
- jdbc:mysql://mysqldb:3307/practice
- jdbc:mysql://mysqldb/practice
- jdbc:mysql://host.docker.internal:3306/practice
- jdbc:mysql://host.docker.internal:3307/practice
None of this worked, but I was able to connect to localhost:3306
and localhost:3307
.
Below is my spring boot code. When I am trying to connect through the Spring Boot application, I was getting the following error.
com.mysql.cj.jdbc.exceptions.CommunicationsException:Communication link failure
The problem over here is when I am trying to connect to localhost the application is up and working, but when trying to connect to mysql container, I was not able to connect.
CodePudding user response:
Check your network to ensure that the application network is connected to the MySQL network
CodePudding user response:
The problem was resolved by changing the port to 6033 and the host to 'localhost.' then you able to login to the MySQL server using the account 'root':
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:6033/app_db?allowPublicKeyRetrieval=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=your_pass