【Docker】之安装MySQL8并挂载数据

下载镜像

   MySQL Community Downloads

# docker从仓库中拉取最新版的mysql镜像,默认获取最新的版本
  docker pull mysql
# docker pull mysql:8.0.28

创建挂载目录

mkdir -p  ~/dockerdata/mysql8/{data,logs,mysql-files,conf}
chmod -R 755 ~/dockerdata/mysql8/
chmod 644 /dockerdata/mysql8/my.cnf

新建my.cnf

vi ~/dockerdata/mysql8/my.cnf

[client]
#socket = /usr/mysql/mysqld.sock
default-character-set = utf8mb4

[mysql]
default-character-set=utf8mb4

[mysqld]
user=mysql
#pid-file        = /var/run/mysqld/mysqld.pid
#socket          = /var/run/mysqld/mysqld.sock
#datadir         = /var/lib/mysql

#socket = /usr/mysql/mysqld.sock
#pid-file = /usr/mysql/mysqld.pid
#datadir  = /usr/mysql/data

# 创建新表时将使用的默认存储引擎
default-storage-engine=INNODB
lower_case_table_names=1
max_allowed_packet=16M

#忘记密码时使用
#skip-grant-tables
#设置协议认证方式
default_authentication_plugin=mysql_native_password
secure_file_priv=/var/lib/mysql
expire_logs_days=7
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
max_connections=1000

general_log = 1
general_log_file = /var/log/mysql/access.log
log-error = /var/log/mysql/error.log

character_set_server = utf8mb4
collation_server = utf8mb4_bin
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Custom config should go here
# !includedir /etc/mysql/conf.d/

创建 MySQL 容器并启动

docker run --restart=always --privileged=true -p 3307:3306 --name mysql8 \
--net mynet --ip 172.172.0.5  \
-e TZ="Asia/Shanghai" \
-v /etc/localtime:/etc/localtime:ro \
-v /root/dockerdata/mysql8/conf:/etc/mysql/conf.d \
-v /root/dockerdata/mysql8/data:/var/lib/mysql \
# secure_file_priv
#-v /root/dockerdata/mysql8/mysql-files:/var/lib/mysql-files \
-v /root/dockerdata/mysql8/logs:/var/log/mysql \
-e MYSQL_ROOT_PASSWORD=12345678 \
-d mysql:8.0.28

-v /root/dockerdata/mysql8/my.cnf:/etc/mysql/my.cnf \

参数说明:
–restart=always: 当Docker 重启时,容器会自动启动。
–privileged=true:容器内的root拥有真正root权限,否则容器内root只是外部普通用户权限
-v /root/dockerdata/mysql8/conf/my.cnf:/etc/my.cnf:映射配置文件
-v /root/dockerdata/mysql8/data/:/var/lib/mysql:映射数据目录

注意:启动mysql报如下错误,那是因为MYSQL新特性secure_file_priv对读写文件的影响。

解决问题:
windows下:修改my.ini 在[mysqld]内加入secure_file_priv=/var/lib/mysql
linux下: 修改my.cnf 在[mysqld]内加入secure_file_priv=/var/lib/mysql

登录容器

docker exec -it mysql8 /bin/bash

mysql -uroot -p12345678

USE mysql;

ALTER USER 'root'@'localhost' IDENTIFIED BY '12345678';
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '12345678';

grant all privileges on *.* to 'root'@'%' with grant option;

CREATE USER 'leeze'@'%' IDENTIFIED with mysql_native_password  BY '12345678';
grant all privileges on *.* to 'leeze'@'%'
flush privileges;

PS

docker安装mysql挂载外部配置和数据目录
Docker安装MySQL5和MySQL8
写最好的Docker安装最新版MySQL8(mysql-8.0.31)教程