侧边栏壁纸
  • 累计撰写 91 篇文章
  • 累计创建 35 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

docker配置之Dockerfile详解

天明
2023-10-25 / 0 评论 / 0 点赞 / 28 阅读 / 3864 字 / 正在检测是否收录...

1、FROM 构建一个属于自己的镜像需要依赖一个基础镜像,就是指定一个官方提供的一个base image。在这个基础之上构建。例如使用daocloud.io提供的centos7作为基础镜像.FROM必须是第一行

FROM daocloud.io/centos:7

2、LABEL 一些注释信息,多行的话可以使用反斜线,以下三种方式

# Set one or more individual labels
LABEL com.example.version="0.0.1-beta"
LABEL vendor="ACME Incorporated"
LABEL com.example.release-date="2015-02-12"
LABEL com.example.version.is-production=""

# Set multiple labels on one line
LABEL com.example.version="0.0.1-beta" com.example.release-date="2015-02-12"

# Set multiple labels at once, using line-continuation characters to break long lines
LABEL vendor=ACME\ Incorporated \
      com.example.is-beta= \
      com.example.is-production="" \
      com.example.version="0.0.1-beta" \
      com.example.release-date="2015-02-12"

3、RUN
RUN 后面要加上要构建镜像时,所要执行的脚本,多行命令换行也可以使用反斜线 \ 来分隔,例如在centos7上安装并启用httpd

RUN yum -y install httpd \
      systemctl enable httpd.service

×需要注意,如果每一行RUN 命令都是单独存在的
例如如下情况

RUN yum update
RUN yum install -y httpd

这种情况下构建之后,如果修改了第二句话

RUN yum update
RUN yum install -y httpd nginx

如果基于修改后的dockerfile构建新镜像,则不会安装新的源里的httpd和nginx,因为第一行没有变化,docker默认认为可使用缓存,所以第一句update不会执行,为了避免这种情况,建议使用反斜线 分隔命令行,这样docker会认为是一句话

RUN yum update \
    yum install -y httpd nginx

4、pipes 管道
RUN 中 使用|管道,

RUN wget -O - https://some.site | wc -l > /number

docker利用/bin/sh -c 执行RUN后面的命令,且只会判定最后一个命令执行结果来判断是否RUN正常执行,例如wc -l成功,但是wget失败,docker也会认为RUN执行成功而制作一个镜像,为了避免,我们可以在命令之前加上set -o pipefail,任意后面失败都会导致构建失败

RUN set -o pipefail && wget -O - https://some.site | wc -l > /number

不是所有shell都支持 set -o pipefail,bash支持,docker默认用/bin/sh ,可以在RUN后面显示的指定所用的shell

RUN ["/bin/bash", "-c", "set -o pipefail && wget -O - https://some.site | wc -l > /number"]

5、CMD
CMD是运行容器时所需要执行的脚本,不同于RUN,RUN是构建镜像时需要执行的脚本。一般服务类型的镜像推荐使用CMD,运行时执行开启服务的脚本

6、EXPOSE
容器所要对外曝光的端口,例如httpd 是80

7、ENV
ENV用来设置容器内的环境变量path
用法 ENV 环境变量 环境变量值

ENV PG_MAJOR 9.3
ENV PG_VERSION 9.3.4
RUN curl -SL http://example.com/postgres-$PG_VERSION.tar.xz | tar -xJC /usr/src/postgress && …
ENV PATH /usr/local/postgres-$PG_MAJOR/bin:$PATH

8、COPY 、ADD
ADD src dest,add的src可以是一个url,add会下载到指定目录,add偶尔会根据下载文件格式进行解压,有时候不会解压,很奇怪
COPY SRC DEST从本地指定的src复制至镜像的目录下
可以ADD URL DEST下载,然后RUN tar zxf .tar -C dest解压

ADD http://example.com/big.tar.xz /usr/src/things/
RUN tar -xJf /usr/src/things/big.tar.xz -C /usr/src/things
RUN make -C /usr/src/things all
0

评论区