0
votes

I have a Spring/Hibernate app that was running with h2-database. Now, I need to make it connect to a Mysql database running on a Docker container.

The Mysql container is derived directly from Dockerhub page.

docker run --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -e MYSQL_DATABASE=test -d mysql:latest

In my application.properties I have:

spring.jpa.hibernate.ddl-auto=create
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=my-secret-pw

Right after it starts I get this exception

com.mysql.cj.jdbc.exceptions.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. at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.13.jar:8.0.13] at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.13.jar:8.0.13] at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835) ~[mysql-connector-java-8.0.13.jar:8.0.13] at com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:455) ~[mysql-connector-java-8.0.13.jar:8.0.13] at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240) ~[mysql-connector-java-8.0.13.jar:8.0.13]

The Mysql container seems to be working fine. I can get in and see it running.

So, where the problem might be?

2

2 Answers

2
votes

You have to publish the port 3306 from your docker instance in order to be able to connect to it from the outside.

docker run --name some-mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=my-secret-pw -e MYSQL_DATABASE=test -d mysql:latest

0
votes

JDBC Url needs a change, you need to replace the localhost with mysql container name some-mysql

spring.datasource.url=jdbc:mysql://some-mysql:3306/test?autoReconnect=true&useSSL=false

Expose your MYSQL port in the command, and run with below.

docker run --name some-mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=test -e MYSQL_USER=user -e MYSQL_PASSWORD=password -d mysql:latest