javamysqldockerjdbcufw

java.sql.SQLException when connecting to MySQL in Docker after changing UFW settings


The below is part of my code which is run inside a Docker container. I have already created the variables before.

String mysqlUrl = "jdbc:mysql://" + mysqlHost + "/" + mysqlDatabase + "?user=" + mysqlUser + "&password=" + mysqlPass;
try {
    mysqlConnection = DriverManager.getConnection(mysqlUrl);
} catch (SQLException e) {
    e.printStackTrace();
}

The below is the error:

java.sql.SQLException: Access denied for user 'myusername'@'_gateway' (using password: YES)

Let me explain what I have done:

My code had worked perfectly fine. However, after I did some changes to my UFW settings that tell UFW to manage the incoming requests to all Docker containers, that error happened. I followed this answer to modify the UFW settings: https://stackoverflow.com/a/51741599/14772173.

Things I have already tried:

I have already opened UFW port 3306. I can confirm that my MySQL username and password are correct, and my database accepts remote connections from all IP addresses.

bind-address = 0.0.0.0

MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '';
+-----------------+-----------+
| User            | Host      |
+-----------------+-----------+
| myusername      | %         |
| root            | localhost |
+-----------------+-----------+
2 rows in set (0.001 sec)

I can confirm that my Docker container can access the external Internet because it can send requests to google.com and can respond to requests from the ping tools and status monitors.

Please help explain why my code can't connect to MySQL databases outside the Docker and how can I fix the problem. Thank you very much.


Solution

  • After specifying the port number like below, my code works. I thought the port number is optional.

    String mysqlUrl = "jdbc:mysql://" + mysqlHost + ":3306/" + mysqlDatabase + "?user=" + mysqlUser + "&password=" + mysqlPass;
    try {
        mysqlConnection = DriverManager.getConnection(mysqlUrl);
    } catch (SQLException e) {
        e.printStackTrace();
    }