docker安装mysql8挂载本地

首先拉取mysql镜像,直接默认拉取最新版本

git pull mysql 
复制代码

查看当前镜像

docker images -a
复制代码

显示已经有mysql镜像了

kiys@kiydeMacBook-Pro ~ % docker images -a
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
mysql        latest    ecac195d15af   3 weeks ago   516MB
复制代码

使用镜像创建一个mysql容器挂载到本地目录
先创建一个存放mysql容器的文件夹
~/docker/mysql/docker-mysql挂在到本地.md 文件夹说明
~/docker/mysql 存放mysql容器
~/docker/mysql/mysql_data 存放挂在到本地的文件

docker-compose.yml docker-mysql挂在到本地.md mysql_data
复制代码

docker-mysql.yml的配置内容

# Use root/example as user/password credentials
version: "3.1"
services:
  mysql_8:
    image: mysql 镜像名称
    container_name: mysql_8 容器名称
    environment:
      - MYSQL_ROOT_PASSWORD=123456 密码
      - MYSQL_DATABASE=base
      - MYSQL_USER=dbuser
      - MYSQL_PASSWORD=topsecret
      - MYSQL_PORT=3306 端口
    ports:
      - "3306:3306" 端口映射
    volumes:
      - ./mysql_data:/var/lib/mysql 挂载路径
复制代码

接下来使用docker-compose run 创建并运行容器 -d 守护运行
查询当前运行的容器

docker ps -a
复制代码
CONTAINER ID   IMAGE     COMMAND                  CREATED       STATUS       PORTS                               NAMES
bb2afd6856cc   mysql     "docker-entrypoint.s…"   2 hours ago   Up 2 hours   0.0.0.0:3306->3306/tcp, 33060/tcp   mysql_8
复制代码

这样mysql就运行起来了
现在在外边使用工具连接

2059 - Authentication plugin 'caching_sha2_password' cannot be loaded: dlope
复制代码

这是加密类型不兼容 不修改root 新增一个支持的可供全部连接的账号
先查询当前运行的容器

docker ps -a
复制代码
CONTAINER ID   IMAGE     COMMAND                  CREATED       STATUS       PORTS                               NAMES
bb2afd6856cc   mysql     "docker-entrypoint.s…"   2 hours ago   Up 2 hours   0.0.0.0:3306->3306/tcp, 33060/tcp   mysql_8
复制代码

获取到id后 进入这个容器进行操作

docker exec -it bb2(容器id) /bin/bash
复制代码

这样就进入容器了

root@bb2afd6856cc:/#
复制代码

接下来就是一系列的mysql操作
首先先登录mysql

mysql -uroot -p
复制代码
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 16
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> 
复制代码

切换数据库

use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql>
复制代码

查看数据库表

show tables;
复制代码

新建一个用户

create user 'admin'@'%'(% 代表任何ip都可以连接 localhost 就只能本地连接)  identified by 'admin0.'(mysql8 必须设置强类型密码 字母数字加符号)
复制代码

给用户授权

grant all privileges on *.* to 'admin'@'%' width gant option; 
复制代码

刷新权限

flush privileges;
复制代码

修改用户加密规则

alter user 'admin'@'%' identified with mysql_native_password by 'admin0.';
复制代码