简体   繁体   中英

SQLException: Access denied when connecting to mysql in docker

I want to deploy a springboot application into a Docker container running mysql. The application has to connect to mysql in the startup process and I am using ormlite library in order to do so. Even though the process works fine outside the container, once I try to deploy the war inside the container I get the following Exception: java.sql.SQLException: Access denied for user 'root'@'localhost'. MySQL is running and port 3306 is exposed in the Dockerfile. Below is my Dockerfile:

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"  

while the script tomcat.sh is:

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

EDIT

I've written a python script in order to check if there was something wrong with mysql but I was able to successfully connect to the database. I've also tried with a simple jar that only has to connect to the db but the error is still the same. Here is the code I'm using:

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

It seems that docker or jdbc (also using a newer version of jdbc connector was not helpful) don't like when you try to connect to mysql using the same user you have used to login. Basically the solution was to create a new user in the mysql database and connect to the database using that user. Below the code I have used:

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");

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