使用 dockerfile 创建镜像

dockerfile 是一个文本格式的配置文件,可以使用 dockerfile 快速创建自定义的镜像。

dockerfile 一般包含4部分信息:基础镜像信息、维护者信息、镜像操作指令、容器启动时执行指令

创建镜像命令:docker build [选项] 路径,会读取指定路径下(包括子目录)的dockerfile,并将该路径下所有内容发送给 docker 服务端,有服务端来创建镜像。因此最好将dockerfile 单独放到一个文件夹下。可以使用 -t 选项来指定生成的镜像标签。

1.1 第一条语句必须是FROM,可以是现成的基础镜像。比较特殊的是 scratch ,他并不实际存在,是一个空白镜像。接下来所写的指令将作为镜像的第一层开始存在。

1.2 RUN指令,用来执行命令行命令。有两种格式

1.2.1 shell 格式:就像直接在命令行中输入的命令一样,比如:

RUN echo "<html> <body><h1> hello Docker! </h1></body> </html>" > /usr/share/nginx/html/index.html

将语句打印到文件中

1.2.2 exec 格式:RUN [ "可执行文件", "参数1", " 参数2"]

1.3 Dockerfile 支持 shell 行尾添加 "" 命令换行方式,以及行首 "#" 进行注释的格式

说明:在构建镜像后将不需要的东西删除掉,减少容器容量。每执行一条指令会构建一个应用层。

1 例子:创建 mysql5.7 版本的镜像,不同于官网的mysql5.7 版本是官网使用字符集是 latin1,对于中文用户来说很是不便。

下面是官网docker 镜像的字符集

接下来创建自己的 Dockerfile 和 my.cnf 配置文件

1.1 新建一个目录用于存放dockerfile

mkdir -p dockerfile/mysql5.7

 进入配置目录

cd dockerfile/mysql5.7

新建所需文件

touch my.conf Dockerfile

1.2 编辑 my.cnf文件,是参照了官网的配置文件后,仅修改了字符编码。

vi my.cnf

内容如下:

//my.cnf
# CLIENT SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by MySQL client applications.
# Note that only client applications shipped by MySQL are guaranteed
# to read this section. If you want your own MySQL client program to
# honor these values, you need to specify it as an option during the
# MySQL client library initialization.
[client]

# pipe
# socket=0.0
port=3306


[mysql]
default-character-set=utf8


# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this 
# file.
#
# server_type=3
[mysqld]
# The TCP/IP Port the MySQL Server will listen on
port=3306

# The default character set that will be used when a new schema or table is
# created and no character set is defined
character-set-server=utf8

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

1.3 编辑 Dockerfile,删除默认配置文件,将自定义配置文件复制到配置文件夹中

//Dockerfile
FROM mysql:5.7
RUN rm -rf /etc/mysql
RUN mkdir /etc/mysql
COPY my.cnf /etc/mysql/

CMD ["mysqld", "--character-set-server=utf8", "--collation-server=utf8_unicode_ci"]

1.4 进行docker构建

ls
Dockerfile  my.conf

docker build . -t mysql5.7

此时可以看到构建的image

1.5 进行测试,

运行容器

docker run --name some-mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag

运行后进入容器可以看到字符编码

构建成功!!!

原文地址:https://www.cnblogs.com/zhaopengcheng/p/8366294.html