0

I have a mac running mysql on localhost:3306. I am trying to connect to it via a Spring Beans App (Java) but am getting errors. Can anyone please assist? I am doing:

String jdbc_url = "jdbc:mysql://" + hostname + "/" + database;
try (Connection conn = DriverManager.getConnection(jdbc_url, db_username, db_password)) {
... my code here ...
}

I have tried String jdbc_url = "jdbc:mysql://docker-mysql:3306/mydb" but I got:

ocessing failed; nested exception is 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.] with root cause

java.net.ConnectException: Connection timed out

I have also tried: "mysql+mysqlconnector://root:mypassword@host.docker.internal:3306/mydb"; but I got the error:

java.sql.SQLException: No suitable driver found for mysql+mysqlconnector://root:mypassword@host.docker.internal:3306/mydb

I also tried:

jdbc:mysql://localhost:3306/mydb

but this failed as well because (I think) localhost is the localhost of the docker container and NOT my local machine.

HeronAlgoSearch
  • 1,581
  • 2
  • 18
  • 35
  • Is your spring application residing inside the same host where you are having docker container? The first error indicates a connectivity issue between spring application and MySQL hosted on docker whereas the second one indicates invalid jdbc connection string url. – Kavitha Karunakaran Feb 17 '21 at 17:06
  • Which part of this (or both, or neither) are running in containers? If both, how are you starting the containers? – David Maze Feb 17 '21 at 17:42

2 Answers2

0

I would start at this other question. Its not exactly the same but many of the concepts in the answer apply to your situation. If you still have issues, you may want to check your local firewall as well to make sure its not blocking the ports.

Ben Lusk
  • 34
  • 6
0

Found the solution (thank you Allow docker container to connect to a local/host postgres database !)

In short do:

String hostname = "host.docker.internal:3306"; //if your port is not 3306 then naturally change it here
String database = "yourdb";
String jdbc_url = "jdbc:mysql://" + hostname + "/" + database;
try (Connection conn = DriverManager.getConnection(jdbc_url, db_username, db_password)) {
... your code here ...
}
HeronAlgoSearch
  • 1,581
  • 2
  • 18
  • 35