首页 > 解决方案 > 在没有主机模式的情况下,从 docker 到 localhost 的 mysql 的 jdbc url 不起作用

问题描述

我有一个连接到本地 MySQL 的本地 Spring Boot 应用程序,它工作正常。

对于连接,我使用以下属性:

spring.datasource.url=jdbc:mysql://localhost:3306/pitstop?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC

我想将我的应用程序放在 docker 中并尝试连接到本地数据库。
所以我需要修改 MySQL url

我用这个命令获取本地IP ip route show | grep "default" | awk '{print $3}',结果是192.168.1.1。我像这样修改我的网址

spring.datasource.url=jdbc:mysql://192.168.1.1:3306/pitstop?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC

并尝试通过命令使用我的应用程序启动 docker 容器,docker run -p 9001:9001 --network=bizon4ik --rm bizon4ik/mycontainer结果是异常:

Caused by: 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.

我试图找到另一个IP。我使用ip addr show命令并找到了下一条记录:

 3: wlp3s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 30:52:cb:db:8d:e0 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.102/24 brd 192.168.1.255 scope global dynamic noprefixroute wlp3s0

所以基于它我192.168.1.102修改了我的网址,但结果是同样的例外。

为了确保创建的 IP 是正确的,我使用纯 ubuntu 运行新的一个容器docker run -it --rm --network=bizon4ik ubuntu并检查上述 IP:

root@268c4d544328:/# nmap -p 3306 192.168.1.1

Starting Nmap 7.60 ( https://nmap.org ) at 2019-07-28 17:28 UTC
Nmap scan report for 192.168.1.1
Host is up (0.053s latency).

PORT     STATE    SERVICE
3306/tcp filtered mysql
root@268c4d544328:/# nmap -p 3306 192.168.1.102   

Starting Nmap 7.60 ( https://nmap.org ) at 2019-07-28 15:56 UTC
Nmap scan report for my-host (192.168.1.102)
Host is up (0.000088s latency).

PORT     STATE  SERVICE
3306/tcp closed mysql

看起来不错,ubuntu 容器可以 ping 我的数据库。您对为什么我无法通过应用程序连接到数据库有任何想法吗?

注意:

我在数据库中检查SHOW GRANTS;了结果是GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION

我还检查了/etc/mysql/my.cnf文件。它只有这些记录:

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

我没有~/.my.cnf

标签: javamysqldockerjdbc

解决方案


问题出在bind-addressMySQL 上。但是我看了看/etc/mysql/my.cnf,正确的地方是/etc/mysql/mysql.conf.d/mysqld.cnf


推荐阅读