SQLException:连接到 docker 中的 mysql 时访问被拒绝

SQLException: Access denied when connecting to mysql in docker

我想将 springboot 应用程序部署到 Docker 容器 运行 mysql。应用程序必须在启动过程中连接到 mysql,为此我正在使用 ormlite 库。尽管该过程在容器外运行良好,但一旦我尝试在容器内部署 war,我就会收到以下异常: java.sql.SQLException:用户 'root'@'localhost' 的访问被拒绝。 MySQL 是 运行 并且端口 3306 在 Docker 文件中公开。 下面是我的 Docker 文件:

FROM mydocker:latest1
MAINTAINER DockerFan version 1.0
ADD tomcat.sh /bin/tomcat.sh
ADD application1.war /etc/apache-tomcat-9.0.12/webapps/application1.war
ADD application2.war /etc/apache-tomcat-9.0.12/webapps/application2.war
EXPOSE 8080
EXPOSE 3306
ENTRYPOINT "/bin/tomcat.sh"  

而脚本 tomcat.sh 是:

bash /etc/init.d/mysql start 
sleep 10
bash /etc/apache-tomcat-9.0.12/bin/catalina.sh run 

编辑

我写了一个 python 脚本来检查 mysql 是否有问题,但我能够成功连接到数据库。 我也试过一个简单的 jar,它只需要连接到数据库,但错误仍然是一样的。这是我正在使用的代码:

String databaseURL = "jdbc:mysql://localhost/db_name?user=root&password=password"
connection = new JdbcConnectionSource(databaseURL);

似乎 docker 或 jdbc(也使用较新版本的 jdbc 连接器没有帮助)在您尝试连接到 mysql 使用您用于登录的同一用户。基本上解决方案是在 mysql 数据库中创建一个新用户并使用该用户连接到数据库。在我使用的代码下方:

Driver driver = (Driver) Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection conn = null;
DriverManager.getConnection("jdbc:mysql://localhost/user=newuser&password=password");
System.out.println("Connected to database");