首页 > 解决方案 > Why I can't connect to mysql docker container through JDBC with another database user than root?

问题描述

I am using official docker container from mysql.

I've run docker container with this commands]:

sudo docker run -d --name desarrollo -p 3306:3306 -h localhost -e MYSQL_ROOT_PASSWORD=admin --mount src=mysql-desarrollo,dst=/var/lib/mysql mysq

Then I connected:

sudo docker exec -it desarrollo mysql -u root -p

It worked. Althougth I don't know why I have a root user with host '%'

mysql> select user, host from mysql.user;
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| root             | %         |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
5 rows in set (0.00 sec)

Then I performed these sentences for create a database and its user:

create database my_database CHARACTER SET utf8 COLLATE utf8_bin;
create user 'my_user'@'localhost' identified by 'my_password';
grant ALL PRIVILEGES ON *.* TO 'my_user'@'localhost';

I asignned all privileges because when I only asignned privileges over my created database it didn't work.

Now, When I try to connect with my_user user through JDB it doesn't work but with root user it works (It was tested with internal client on Intellij IDE). This the JDBC url:

jdbc:mysql://localhost:3306/my_database

Thanks in advance for your help!

标签: mysqldocker

解决方案


这可能是因为您my_user被允许从localhost. 但这localhost在 docker 容器中被引用。但是您正试图从主机 PC 访问。因此,将其替换为您的 PC IP 地址或使用通配符即可。

create user 'my_user'@'%' identified by 'my_password';

推荐阅读