1、首先需要拉取对应镜像(不指定版本号默认最新,本案例中使用的是8.0.26版本)

docker pull mysql:8.0.26

2、然后需要在宿主机上创建对应的文件夹用于容易挂载,易于管理MySQL配置文件等,(当前操作目录是在/home下),创建mysql目录并进入创建conf,data两个目录

mkdir -p mysql && cd $_ && mkdir {conf,data}

3、创建我们的my.cnf文件,放在我们刚刚创建的conf下面

cd conf
touch my.cnf

 复制以下内容并粘贴到my.cnf中保存起来

# Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.

#

# This program is free software; you can redistribute it and/or modify

# it under the terms of the GNU General Public License as published by

# the Free Software Foundation; version 2 of the License.

#

# This program is distributed in the hope that it will be useful,

# but WITHOUT ANY WARRANTY; without even the implied warranty of

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

# GNU General Public License for more details.

#

# You should have received a copy of the GNU General Public License

# along with this program; if not, write to the Free Software

# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

#

# The MySQL Server configuration file.

#

# For explanations see

# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

[mysqld]

pid-file = /var/run/mysqld/mysqld.pid

socket = /var/run/mysqld/mysqld.sock

datadir = /var/lib/mysql

secure-file-priv= NULL

# Disabling symbolic-links is recommended to prevent assorted security risks

symbolic-links=0

# Custom config should go here

!includedir /etc/mysql/conf.d/

max_connections=1000
wait_timeout=120
interactive_timeout=300

lower_case_table_names=1

4、开始创建MySQL容器

docker run --restart=unless-stopped -d --name mysql -p 3306:3306 -v /home/mysql/conf/my.cnf:/etc/mysql/my.cnf -v /home/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root mysql:8.0.26

5、目前mysql容器启动成功以后,我们远程连接还是会报错的,由于mysql8加密规则问题,我们需要进入到mysql中进行修改加密规则以及更新用户密码再刷新一下权限即可

docker exec -it mysql /bin/bash
mysql -uroot -p
输入mysql容器创建时指定的密码(-e MYSQL_ROOT_PASSWORD=root):root
use mysql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '新密码';
FLUSH PRIVILEGES;

注意:此处修改的是root的localhost方式,可以查看是否可以远程连接,如果不能,可继续设置如下  

ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '新密码';

6、此时就可以进行远程连接啦!!!

Logo

更多推荐