# docker从仓库中拉取最新版的mysql镜像,如果没加标签的话,默认获取最新的版本
Docker pull mysql
# 创建挂载的目录,最好创建在home目录下,否则可能会有管理员访问权限的问题,因为docker容器中是普通用户
mkdir -p /home/docker/mysql/conf && mkdir -p /home/docker/mysql/data
# 把mysql临时运行起来,这时候mysql是还没有挂载数据卷的,为了取出 my.cnf文件
docker run --name mysqltest -p 3307:3306 -e MYSQL_ROOT_PASSWORD=root -d mysql
# 复制my.cnf文件到本地目录,取出之后之前的运行的mysql容器就可以删除了
docker cp mysqltest:/etc/mysql/my.cnf /home/docker/mysql/conf
# 启动mysql挂载数据卷,--restart=on-failure:3是指容器在未来出现异常退出(退出码非0)的情况下循环重启3次
docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -v /home/docker/mysql/conf/my.cnf:/etc/mysql/my.cnf -v /home/docker/mysql/data:/var/lib/mysql --restart=on-failure:3 -d mysql
# 如果远程访问不了,则进行以下操作,进入容器中,设置远程访问
docker exec -it mysql bash
# 登录mysql
mysql -uroot -p123456
# 切换到mysql数据库
use mysql;
# 查询user表,如果有两个root用户,删除掉host=%的root数据,再修改localhost为%
select host, user, authentication_string, plugin from user;
delete from user where host="%" and user="root";
update user set host = '%' where user = 'root';
alter user 'root'@'%' identified with mysql_native_password by '123456';
# 立即生效
FLUSH PRIVILEGES;
另一种方法,目录建到usr下的
mkdir -pm 777 /usr/local/docker/mysql
mkdir -pm 777 /usr/local/docker/mysql/conf
mkdir -pm 777 /usr/local/docker/mysql/logs
mkdir -pm 777 /usr/local/docker/mysql/data
mkdir -pm 777 /usr/local/docker/mysql/mysql-files
# 一样复制my.cnf文件到目录下
docker cp mysql:/etc/my.cnf /usr/local/docker/mysql/conf/my.cnf
docker pull mysql
# --privileged=true:授予管理员权限
docker run -p 3306:3306 --privileged=true --name mysql -v /usr/local/docker/mysql/conf/my.cnf:/etc/mysql/my.cnf -v /usr/local/docker/mysql/conf:/etc/mysql -v /usr/local/docker/mysql/logs:/var/log/mysql -v /usr/local/docker/mysql/mysql-files:/var/lib/mysql-files -v /usr/local/docker/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 -d mysql