简体   繁体   中英

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.

I want connect to host database

( host : Ubuntu/18.04.5 LTS (Bionic Beaver))

( database : mysql Ver 14.14 Distrib 5.7.35, for Linux (x86_64) using EditLine wrapper)

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 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

$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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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