简体   繁体   English

Java JDBC 在 docker 中连接无法连接到主机数据库

[英]Java JDBC connecting in docker can't connect to host database

I have a Maven container running Spring Boot and connecting to a database with JDBC.我有一个 Maven 容器运行 Spring Boot 并使用 JDBC 连接到数据库。

I want connect to host database我想连接到主机数据库

( host : Ubuntu/18.04.5 LTS (Bionic Beaver)) 主机:Ubuntu/18.04.5 LTS(仿生海狸))

( database : mysql Ver 14.14 Distrib 5.7.35, for Linux (x86_64) using EditLine wrapper) 数据库:mysql Ver 14.14 Distrib 5.7.35,用于 Linux (x86_64) 使用 EditLine 包装器)

This is my connection string这是我的连接字符串

this.conn = DriverManager.getConnection("jdbc:mysql://172.24.0.1:3306/myDB?"+"user=xxxx&password=xxxx");

This is my container IP这是我的容器 IP

$ip route show
default via 172.24.0.1 dev eth0
172.24.0.0/16 dev eth0 proto kernel scope link src 172.24.0.10

I can te.net and mysql login with IP 172.24.0.1 or 172.17.0.1 in Maven container我可以在 Maven 容器中使用 IP 172.24.0.1 或 172.17.0.1 登录 te.net 和 mysql

$telnet 172.24.0.1 3306
Trying 172.24.0.1...
Connected to 172.24.0.1.
Escape character is '^]'.

telnet 172.17.0.1 3306
Trying 172.17.0.1...
Connected to 172.17.0.1.
Escape character is '^]'.

However, I can't connect via JDBC with IP 172.24.0.1 or 172.17.0.1.但是,我无法通过 JDBC 连接到 IP 172.24.0.1 或 172.17.0.1。

If you want to connect to the database that is installed on the host machine where your docker image runs, then the host name in your connection string should be host.docker.internal.如果要连接到运行 docker 映像的主机上安装的数据库,则连接字符串中的主机名应为 host.docker.internal。

DriverManager.getConnection("jdbc:mysql://host.docker.internal:3306/myDB?"+"user=xxxx&password=xxxx");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM