gpt4 book ai didi

docker - 如何在不使用 ADD 或 COPY 指令的情况下将文件添加到 Dockerfile 中的图像

转载 作者:IT老高 更新时间:2023-10-28 12:41:51 25 4
gpt4 key购买 nike

我需要 Docker 容器中的大型 *.zip 文件 (5 gb) 的内容来编译程序。 *.zip 文件位于我的本地计算机上。这样做的策略是:

COPY program.zip /tmp/
RUN cd /tmp \
&& unzip program.zip \
&& make

完成此操作后,我想删除解压缩的目录和原始 *.zip 文件,因为不再需要它们。问题是 COPY(以及 ADD 指令)将向图像添加一个层,该层将包含文件 program.zip是有问题的,因为图像可能至少有 5GB 大。有没有办法在不使用 COPYADD 指令的情况下将文件添加到容器中? wget 将不起作用,因为提到的 *.zip 文件在我的本地机器上并且 curl file://localhost/home/user/program.zip -o/tmp/program.zip 也不起作用。

最佳答案

这并不简单,但可以通过 wgetcurl 完成,并得到 python 的一点支持。 (所有三个工具通常都应该在 *nix 系统上可用。)

当没有给出 url 并且

时,

wget 将不起作用

 curl file://localhost/home/user/program.zip -o /tmp/

不能在 DockerfileRUN 指令中工作。因此,我们需要一个 wgetcurl 可以访问和下载 program.zip 的服务器。

为此,我们设置了一个小型 python 服务器,它为我们的 http 请求提供服务。为此,我们将使用 python 中的 http.server 模块。 (您可以使用 pythonpython 3。两者都可以使用。

python -m http.server --bind 192.168.178.20 8000

python 服务器将在它启动的目录中提供所有文件。因此,您应该确保在您要在镜像构建期间下载的文件所在的目录中启动服务器在或创建一个包含您的程序的临时目录。为了便于说明,让我们创建文件 foo.txt,稍后我们将在 Dockerfile 中通过 wget 下载该文件:

echo "foo bar" > foo.txt

在启动 http 服务器时,指定 LAN 上本地计算机的 IP 地址很重要。此外,我们将打开端口 8000。完成此操作后,我们应该会看到以下输出:

python3 -m http.server --bind 192.168.178.20 8000
Serving HTTP on 192.168.178.20 port 8000 ...

现在我们构建一个 Dockerfile 来说明它是如何工作的。 (我们假设文件 foo.txt 应该被下载到 /tmp 中):

FROM debian:latest
RUN apt-get update -qq \
&& apt-get install -y wget
RUN cd /tmp \
&& wget http://192.168.178.20:8000/foo.txt

现在我们开始构建

docker build -t test .

在构建期间,您将在我们的 python 服务器上看到以下输出:

172.17.0.21 - - [01/Nov/2014 23:32:37] "GET /foo.txt HTTP/1.1" 200 -

我们图像的构建输出将是:

Step 2 : RUN cd /tmp && wget http://192.168.178.20:8000/foo.txt
---> Running in 49c10e0057d5
--2014-11-01 22:56:15-- http://192.168.178.20:8000/foo.txt
Connecting to 192.168.178.20:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 25872 (25K) [text/plain]
Saving to: `foo.txt'

0K .......... .......... ..... 100% 129M=0s

2014-11-01 22:56:15 (129 MB/s) - `foo.txt' saved [25872/25872]

---> 5228517c8641
Removing intermediate container 49c10e0057d5
Successfully built 5228517c8641

然后,您可以通过从刚刚构建的镜像启动并输入容器来检查它是否真的有效:

docker run -i -t --rm test bash

然后您可以在 /tmp 中查找 foo.txt

我们现在可以将任何文件添加到我们的 image 中,而无需创建新层。假设您要添加一个大约 5 GB 的程序,如问题中所述,我们可以这样做:

FROM debian:latest
RUN apt-get update -qq \
&& apt-get install -y wget
RUN cd /tmp \
&& wget http://conventiont:8000/program.zip \
&& unzip program.zip \
&& cd program \
&& make \
&& make install \
&& cd /tmp \
&& rm -f program.zip \
&& rm -rf program

这样我们就不会剩下 10 GB 的垃圾了。

关于docker - 如何在不使用 ADD 或 COPY 指令的情况下将文件添加到 Dockerfile 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26692708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com