Docker 下的 MySQL 管理及连接

本文记录了 Docker 下安装 MySQL 以及容器外部连接管理 MySQL 的方法。

运行一个 MySQL 容器

参照 Docker Hub 上的 MySQL 镜像使用说明:

docker run --name mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -d -p 3306:3306 mysql

通过 docker ps 查看容器是否启动成功:

~ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
7036ba2e08b7        mysql               "docker-entrypoint.s…"   9 minutes ago       Up 9 minutes        0.0.0.0:3306->3306/tcp, 33060/tcp   mysql

授权

首先进入到容器内部:

~ docker exec -it mysql bash

远程授权:

mysql> grant all on *.* to 'root'@'%';

修改加密规则:(这一步可以省略)

mysql> alter user 'root'@'localhost' identified by 'password' password expire never;

更新 root 用户密码:(这一步可以省略)

mysql> alter user 'root'@'%' identified with mysql_native_password by 'my_secret_pw';  # 密码为 my_secret_pw

刷新权限:

mysql> flush privileges;

最后退出容器,测试容器外部连接。连接之前查看 docker 的 ip

~ ip addr
# 找到 docker0
docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:e1:46:e0:be brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
...

安装 mysql-client 之后就可以测试连接了:

~ mysql -h 172.17.0.1 -P 3306 -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.15 MySQL Community Server - GPL

Copyright (c) 2000, 2019, 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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容