如何将 mysql 工作台连接到在 docker 中运行 mysql?

2021-11-20 00:00:00 docker mysql mysql-workbench

我在 docker 容器内使用 mysql 服务器并且能够在 docker 内访问.如何在我的本地(主机)上运行的 mysql 工作台中创建连接.

I am using mysql server inside docker container and able to access inside docker. How to create connection in mysql workbench running on my local(Host Machine).

推荐答案

默认部署后 MySQL 有以下连接限制:

By default after deployment MySQL has following connection restrictions:

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

显然,出于安全考虑,您将无法在 docker 镜像之外连接到它.如果您需要更改它以允许 root 从任何主机连接(例如,出于开发目的),请执行以下操作:

Apparently, for the security purposes you will not be able to connect to it outside of the docker image. If you need to change that to allow root to connect from any host (say, for development purposes), do:

  1. 使用所需的所有端口映射启动您的 mysql 映像:

  1. Start your mysql image with all port mappings required:

docker run -p 3306:3306 --name=mysql57 -d mysql/mysql-server:5.7

或者,如果需要完整的端口映射:

or, if the complete port mapping is required:

docker run -p 3306:3306 -p 33060:33060 --name=mysql57 -d mysql/mysql-server:5.7

  1. 如果这是全新安装 - 获取默认密码:

  1. If this is the fresh installation - grab the default password:

docker logs mysql57 2>&1 |grep 生成

使用mysql客户端直接连接docker中的mysqld:

Connect using mysql client directly to the mysqld in docker:

docker exec -it mysql57 mysql -uroot -p

如果这是全新安装,您将被要求使用 ALTER USER 命令更改密码.做吧.

If this is the fresh installation you will be asked to change the password using ALTER USER command. Do it.

运行 SQL:

update mysql.user set host = '%' where user='root';

退出 mysql 客户端.

重启容器:

docker restart mysql57

现在您将能够从 MySQL Workbench 连接到

Now you will be able to connect from MySQL Workbench to

host: `0.0.0.0` 
port: `3306`

查询将显示所有更改后:

After all the changes the query will show:

select host, user from mysql.user;
+-----------+---------------+
| host      | user          |
+-----------+---------------+
| %         | root          |
| localhost | healthchecker |
| localhost | mysql.session |
| localhost | mysql.sys     |
+-----------+---------------+

相关文章