无法连接在docker容器上运行的mysql服务器

时间:2020-06-09 05:05:00

标签: mysql docker containers

我正在docker容器中运行sql server`

docker pull mysql/mysql-server:latest

docker run --name=my_sql -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=1234 mysql/mysql-server:latest

docker exec -it my_sql mysql -u root -p

#Create table in mysql running in container.
CREATE DATABASE hello_java CHARACTER SET utf8 COLLATE utf8_general_ci;

所有这些都成功完成。 现在,当我尝试使用Java连接到db时,出现了错误。

String url = "jdbc:mysql://192.168.56.101:3306/hello_java";
DriverManager.getConnection(url, "root", "1234");
System.out.println("Connection establised....");

192.168.56.101是我的VM的IP。我在VM上运行Linux。

我收到通讯链接失败错误。

我在Google上搜索后发现很少的解决方案,但没有一个对我有用。

Solving a "communications link failure" with JDBC and MySQL

How to connect with MySQL DB running as container in docker?

我对/etc/my.cnf文件进行了更改,但这似乎无济于事。

谢谢。

1 个答案:

答案 0 :(得分:1)

我做了一些RnD,并找到了以下解决方案。

String url = "jdbc:mysql://192.168.56.101:3306/mysql?allowPublicKeyRetrieval=true&useSSL=false";

在查询中添加allowPublicKeyRetrieval=true&useSSL=false有助于我连接数据库。

以下链接对于解决方案很有用。

Connection Java-MySql : Public Key Retrieval is not allowed

https://www.tutorialspoint.com/how-to-disable-establishing-ssl-connection-without-server-s-identity-verification-is-not-recommended-warning-when-connecting-to-mysql-database-in-java

谢谢。