无法使用 JDBC 连接到 MySQL-服务器 运行 Docker - 通信 Link 失败

cannot connect to MySQL-server running on Docker with JDBC - Communication Link Failure

我有一个带有 PORTS 3306/tcp, 33060-33061/tcp 的 Mysql-server docker 实例。 我试图通过 JDBC 连接到它,但我一直收到错误 Caused by: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure。 我创建了一个用户 test 和一个同样名为 test.

的数据库

我使用的代码如下:

package com.example.testconnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class TestConnection {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/test";
        String username = "test";
        String password = "password";

        System.out.println("Connecting database...");

        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            System.out.println("Database connected!");
        } catch (SQLException e) {
            throw new IllegalStateException("Cannot connect the database!", e);
        }

    }
}

使用 Gradle 构建,具有以下依赖项:

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.0'
    runtimeOnly 'mysql:mysql-connector-java:8.0.25'
}

我错过了什么?

通过使用 docker inspect nameofmycontainer | grep IPAddress 检查 mysql docker 容器并获取 IP 来解决,例如172.17.0.2。把这个IP地址改成Java代码,代入localhost,问题就解决了!

另一件重要的事情是确保用户有权在 localhost 之外进行连接。这可以通过做 GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;