使用docker快速实现一个mysql环境

日常想快速部署一个mysql环境,大多是直接安装一下即可,有时候用的是win系统,还是想使用跟生产环境一样,那建议直接使用docker吧。

下载mysql镜像

第1步:查看已有的镜像:

1
docker images

第2步:如果没有mysql镜像,下载最新的mysql镜像,默认是最新的版本:

1
docker pull mysql

第3步:确认mysql镜像:

下面可以看到多了一个mysqlimage

1
2
3
PS C:\WINDOWS\system32> docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql latest 3218b38490ce 6 months ago 516MB

安装mysql镜像

第1步:安装mysql镜像:

1
docker run --name docker_mysql -p 9306:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mysql

第2步:确认mysql容器:

下面可以看到多了一个mysql的容器。

1
2
3
PS C:\WINDOWS\system32> docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
380f2cced419 mysql "docker-entrypoint.s…" 4 hours ago Up 4 hours 33060/tcp, 0.0.0.0:9306->3306/tcp docker_mysql

查看mysql版本

第1步:进入mysql容器:

1
docker exec -it  380 bash

其中380(前3位或完整都可以)为上面创建mysql容器 ID。

第2步:连接mysql

输入密码后进入mysql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
root@380f2cced419:/# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 15
Server version: 8.0.27 MySQL Community Server - GPL

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

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>

第3步:查看mysql版本:

1
2
3
4
5
6
7
mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.27 |
+-----------+
1 row in set (0.00 sec)

远程连接mysql server

如果远程连接报错:

原因:
mysq8.0以上的版本用户密码加密方式为caching_sha2_password,大部分客户端暂不支持,需要修改下mysql的加密方式。

解决:
1 连接mysql 参考 3:查看mysql版本中的步骤。
2 查看当前的加密方式:

1
2
3
4
5
6
7
mysql> use mysql;
mysql> select user,plugin from user where user='root';
+------+-----------------------+
| user | plugin |
+------+-----------------------+
| root | caching_sha2_password |
| root | caching_sha2_password |

3 修改加密方式

1
2
3
4
5
mysql> alter user 'root'@'%' identified with mysql_native_password by 'lfx23456';
Query OK, 0 rows affected (0.01 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

4 远程连接验证一下: