在镜像中管理文件

Docker 入门

Tim Sangster

Software Engineer @ DataCamp

将文件 COPY 到镜像

COPY 指令将本地机器的文件复制到正在构建的镜像中:

COPY <src-path-on-host> <dest-path-on-image>
COPY /projects/pipeline_v3/pipeline.py /app/pipeline.py
docker build -t pipeline:v3 .
...
[4/4] COPY ./projects/pipeline_v3/pipeline.py /app/pipeline.py

如果目标路径未包含文件名,将沿用源文件名:

COPY /projects/pipeline_v3/pipeline.py /app/
Docker 入门

COPY 文件夹

在源路径中不指定文件名会复制该文件夹的全部内容。

COPY <src-folder> <dest-folder>
COPY /projects/pipeline_v3/ /app/

COPY /projects/pipeline_v3/ /app/ 会复制 pipeline_v3/ 下的所有内容:

/projects/
    pipeline_v3/
        pipeline.py
        requirements.txt
        tests/
            test_pipeline.py
Docker 入门

从父目录复制文件

/init.py
/projects/
    Dockerfile
    pipeline_v3/
        pipeline.py

如果当前工作目录位于 projects/ 文件夹:

将无法把 init.py 复制进镜像:

docker build -t pipeline:v3 .
 => ERROR [4/4] COPY ../init.py /     0.0s
failed to compute cache key: "../init.py" not found: not found
Docker 入门

下载文件

相比从本地目录复制,构建镜像时常在镜像内下载文件:

  • 下载文件

RUN curl <file-url> -o <destination>

  • 解压文件

RUN unzip <dest-folder>/<filename>.zip

  • 删除原始 zip 文件

RUN rm <copy_directory>/<filename>.zip

Docker 入门

高效下载文件

  • 每条下载文件的指令都会增加镜像体积。
  • 即使之后删除这些文件也会增加。
  • 解决方案:在一条指令中完成下载、解压、删除。
RUN curl <file_download_url> -o <destination_directory>/<filename>.zip \
&& unzip <destination_directory>/<filename>.zip -d <unzipped-directory> \
&& rm <destination_directory>/<filename>.zip
Docker 入门

总结

用途 Dockerfile 指令
将主机文件复制到镜像 COPY <src-path-on-host> <dest-path-on-image>
将主机文件夹复制到镜像 COPY <src-folder> <dest-folder>
不能从构建 Dockerfile 的父目录复制 COPY ../<file-in-parent-directory> /

通过在单个 RUN 指令中完成下载、解压与清理来保持镜像精简:

RUN curl <file_download_url> -o <destination_directory> \
&& unzip <destination_directory>/<filename>.zip -d <unzipped-directory> \
&& rm <destination_directory>/<filename>.zip
Docker 入门

Passons à la pratique !

Docker 入门

Preparing Video For Download...