how to use docker (3) Pull an Image from Docker Repository

根据昨天经验,今天再把本地的mysql数据库环境转移到docker

1. pull image

第一步还是要拉镜像版本选择和原环境相同的版本

1
docker pull mysql:5.7.25

2. run image

还是先直接把命令行脚本发出了,我们在一步步详细解说,

1
docker run -dp 3306:3306 --name mysql  -e MYSQL_ROOT_PASSWORD=password -v D:\docker\mysql3306\conf:/etc/mysql/conf.d -v D:\docker\mysql3306\data:/var/lib/mysql mysql:5.7.25

类似相同的功能不说了,看看启动mysql容器时和之前redis有什么不同和需要注意的。

  • 设置root密码

    -e MYSQL_ROOT_PASSWORD=123456

对于/etc/mysql/conf.d这个目录最新官方MySQL(5.7.19)的docker镜像在创建时映射的配置文件目录有所不同,在此记录并分享给大家:

官方原文:

The MySQL startup configuration is specified in the file /etc/mysql/my.cnf, and that file in turn includes any files found in the /etc/mysql/conf.d directory that end with .cnf. Settings in files in this directory will augment and/or override settings in /etc/mysql/my.cnf. If you want to use a customized MySQL configuration, you can create your alternative configuration file in a directory on the host machine and then mount that directory location as /etc/mysql/conf.d inside the mysql container.

大概意思是说:

MySQL(5.7.19)的默认配置文件是 /etc/mysql/my.cnf 文件。如果想要自定义配置,建议向 /etc/mysql/conf.d 目录中创建 .cnf 文件。新建的文件可以任意起名,只要保证后缀名是 cnf 即可。新建的文件中的配置项可以覆盖 /etc/mysql/my.cnf 中的配置项。

通过这条规则,我们可以把有的镜像启动的配置文件挂载到/etc/appname/conf.d这里就可以让镜像中应用使用我们自定义配置启动

这样下来是不是很方便, 不管镜像中默认配置如何只要把自定义配置挂载到指定目录就可以了。

-v D:\docker\mysql3306\data:/var/lib/mysql

宿主机的D:\docker\mysql3306\data 目录挂载到容器/var/lib/mysql的Mysql数据存储目录下。

测试一下,使用mysql客户端连接数据库后新建一个名称为test的空数据库, 可以看到在宿主机的D:\docker\mysql3306\data文件夹下生成了对应的test文件夹
说明配置生效了。

配置linux下mysql时用到的一些命令

  • 查找mysqld
    whereis mysql
  • 查找生效的mysql配置文件
    /usr/sbin/mysqld --verbose --help |grep -A 1 'Default options'
    执行后结果
    1
    2
    3
    4
    root@0f303c0363dc:/# /usr/sbin/mysqld --verbose --help |grep -A 1 'Default options'
    mysqld: [Warning] World-writable config file '/etc/mysql/conf.d/my.cnf' is ignored.
    Default options are read from the following files in the given order:
    /etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf

mysqld: [Warning] World-writable config file ‘/etc/mysql/conf.d/my.cnf’ is ignored.
查了些资料这句要说明意思是/etc/mysql/conf.d/my.cnf 是一个所有人可以读写的文件,为了安全起见忽略这个文件的配置。

注意! 这时候你的配置文件是不起作用的,容器还是按默认配置启动的mysql数据库
处理的这个问题的办法是,进入容器执行下面的命令

1
chmod 644 /etc/mysql/conf.d/my.cnf

然后再重启容器配置文件就可以生效了。

  • 查看mysql对应版本的所有配置项
    1
    docker run -it --rm mysql:tag --verbose --help > help.txt
    然后打开当前目录下的help.txt查看