如何从Docker镜像中复制文件 - Dockerfile CMD

8
在构建时,我想将一个文件从镜像中的文件夹/opt/myApp/myFile.xml复制到我的主机文件夹/opt/temp
在Dockerfile中,我使用--mount如下,尝试挂载到本地的测试文件夹: RUN --mount=target=/opt/temp,type=bind,source=test cp /opt/myApp/myFile.xml /opt/temp 我成功构建了镜像,但本地的test文件夹是空的,有什么想法吗?

顺便提一下,当我打印目标文件夹时,我可以看到文件在那里。“RUN echo $(ls -1 /opt/temp)”问题出在挂载上。本地主机上的测试文件夹中没有看到任何内容。 - Mary1
在Dockerfile中,您可以使用COPY指令。#COPY-Dockerfile - vijay v
@vijay,COPY指令将新文件或目录从<src>复制并添加到容器的路径<dest>的文件系统中。这个问题是相反的:从镜像到主机。 - Neo Anderson
1个回答

6

在构建时不支持将文件从镜像复制到主机。
可以在运行时使用卷轻松实现此操作。

但是,如果你非常想绕过这个限制,可以查看自定义构建输出文档,该文档介绍了支持此类活动的方法。

下面是一个简单的示例,灵感来自官方文档:

Dockerfile

FROM alpine AS stage-a
RUN mkdir -p /opt/temp/
RUN touch /opt/temp/file-created-at-build-time
RUN echo "Content added at build-time" > /opt/temp/file-created-at-build-time

FROM scratch as custom-exporter
COPY --from=stage-a /opt/temp/file-created-at-build-time .

为了使其工作,您需要使用以下参数启动构建命令:
DOCKER_BUILDKIT=1 docker build --output out .

这将在您的主机上创建一个目录out,并生成所需的文件,与Dockerfile放在一起。
.
├── Dockerfile
└── out
    └── file-created-at-build-time

cat out/file-created-at-build-time 
Content added at build-time


现在我注意到自定义构建输出是代替 Docker 镜像的。我需要同时拥有镜像和输出文件。这可行吗? - Mary1
docker build --target stage-a -t stage-a-image-name。这将仅构建stage-a,从stage-a创建一个镜像并跳过stage custom-exporter。我认为您无法一次获得两个输出。 - Neo Anderson
有没有办法关闭/结束自定义导出器阶段?我在这个阶段之后还有更多的代码,必须在最后应用。我需要最后一部分成为我的镜像的一部分:`FROM alpine AS stage-a RUN mkdir -p /opt/temp/ RUN touch /opt/temp/file-created-at-build-time RUN echo "Content added at build-time" > /opt/temp/file-created-at-build-time FROM scratch as custom-exporter COPY --from=stage-a /opt/temp/file-created-at-build-time . CMD /bin/bash myscript.sh` - Mary1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接