由于要修改MySQL的配置文件,在命令行修改每次重启都会失效,所以想修改Docker下的mysql配置文件,这样将其再作为一个镜像保存,以后就可以一劳永逸了。
在Win10的Docker容器中进行vi操作时,没有Linux中的vi操作那么顺畅,所以我打算在启动容器的时候挂载一个数据卷进去。这样,当我们需要在Docker容器内部进行修改文件时,就可以先把文件从Docker容器中复制到Win10中,然后在Win10中修改完毕后,最后再在Docker容器中覆盖改文件,这样就可以达到vi的目的。
在进行以上操作之前,我们需要先通过Docker设置一个共享的驱动器,为什么要先设置呢,因为Win10的权限要求比较高,不允许软件自行共享文件夹。
接下来我们来看Win10如何设置共享数据卷,首先鼠标右击任务栏右下角的Docker小图标,然后选择Settings...菜单,在弹出的界面中点击Shared Drivers选项卡,在右侧勾选需要共享的驱动器,点击Apply按钮即可。如下图所示:
接下来,我们就开始进行MySQL容器的安装
1、拉取镜像
docker pull mysql:5.7.18
2、启动容器
docker run --name mysql-utf8 -p 3306:3306 -v D:/J2EE/docker:/docker -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.7.18
--name mysql-utf8:给容器起个名字叫mysql-utf8
-p 3306:3306: 将容器中的3306端口映射到主机的3306端口
-v D:/J2EE/docker:/docker: 将主机的D:/J2EE/docker目录挂载到容器的/docker
-e MYSQL_ROOT_PASSWORD=123456: 设置mysql的root用户的密码为123456
3、进入容器
docker exec -it 555 /bin/bash
mysql -u root -p
5、查看MySQL字符集
SHOW VARIABLES LIKE 'character_set_%';
SHOW VARIABLES LIKE 'collation_%';
6、下面我们来设置外部访问的编码
SET NAMES 'utf8';
7、复制mysqld.cnf文件到/docker文件夹(在进行复制前需要先退出)
cp /etc/mysql/mysql.conf.d/mysqld.cnf /docker/mysqld.cnf
8、在本机上修改刚才复制的文件
# Copyright (c) 2014, 2016, 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
[mysql]
default-character-set = utf8
[mysql_safe]
default-character-set = utf8
[client]
default-character-set = utf8
[mysqld]
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
datadir = /var/lib/mysql
#log-error = /var/log/mysql/error.log
# By default we only accept connections from localhost
#bind-address = 127.0.0.1
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
init_connect = 'SET NAMES utf8'
character-set-server = utf8
collation-server = utf8_unicode_ci
9、在容器中将刚才修改后的文件覆盖回去
cp /docker/mysqld.cnf /etc/mysql/mysql.conf.d/mysqld.cnf
10、退出并停止容器
docker stop 555
11、基于刚才的容器创建一个新的镜像
docker commit 555 mysql-utf8:5.7.18
12、基于刚才创建的镜像,启动一个新的容器进行测试
docker run --name mysql-utf8-test1 -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mysql-utf8:5.7.18