Docker mysql 可以从内部登录但不能从外部登录

Docker mysql can log in from inside but cannot from outside

所以我创建了一个 mysql 的容器

docker run --name mysqldb -v ~/Documents/docker/mysqldb:/var/lib/mysql -p 3306:3306 -e MYSQL_USER=user -e MYSQL_PASSWORD=pass123 -e MYSQL_DATABASE=students -e MYSQL_ROOT_PASSWORD=pass123 --rm -d mysql/mysql-server:latest

问题是,当我尝试连接 CLI 时,访问被拒绝。我 运行 这样的命令:

mysql -u user -p
Enter password: 
ERROR 1045 (28000): Access denied for user 'user'@'localhost' (using password: YES)

然后奇怪的是,如果我尝试在容器内登录就可以了。

docker exec -it mysqldb bash
bash-4.2# mysql -u user -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 99
Server version: 8.0.22 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

所以我不知道发生了什么...

更新 我遵循了 Andrei Kovrov 的回答,即使它在最后一天工作,现在我得到这个新错误:

ERROR 1045 (28000): Plugin caching_sha2_password could not be loaded: /usr/lib/x86_64-linux-gnu/mariadb19/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory

更新2 我按照以下步骤成功解决了上述错误 1045 问题:

I loged in the container

docker exec -it CONTAINER_ID bash then log into mysql as root

mysql --user=root --password Enter the password for root (Default is 'root') Finally Run:

ALTER USER 'username' IDENTIFIED WITH mysql_native_password BY 'password';

答案来自这个。好的,它解决了我的问题,但暂时的原因是每当我放下容器并再次启动它时,我都会遇到同样的问题 ERROR 1045 (28000): Plugin caching_sha2_password。所以这是一个临时解决方案,但不是最终的和正确的...

尝试mysql -h 127.0.0.1 -P 3306 -u user -p

来自doc

Client programs determine what type of connection to make as follows:

If the host is not specified or is localhost, a connection to the local host occurs:

On Windows, the client connects using shared memory, if the server 
was started with the shared_memory system variable enabled 
to support shared-memory connections.

On Unix, MySQL programs treat the host name localhost specially, 
in a way that is likely different from what you expect compared to other 
network-based programs: the client connects using a Unix socket file. 
The --socket option or the MYSQL_UNIX_PORT environment 
variable may be used to specify the socket name.