我正在考虑使用Docker在持续集成(CI)服务器上构建依赖关系,这样我就不必在代理本身上安装所有运行时和库。

为了实现这一点,我需要将容器内部构建的构建工件复制回主机。这可能吗?


当前回答

如果您使用podman/buildah1,它为将文件从容器复制到主机提供了更大的灵活性,因为它允许您装载容器。

创建容器后,如以下回答所示

podman create --name dummy IMAGE_NAME

现在,我们可以装载整个容器,然后使用几乎每个linux盒子中的cp实用程序将/etc/foobar的内容从容器(虚拟)复制到主机上的/tmp中。所有这些都可以无根地完成。观察:

$ podman unshare -- bash -c '
  mnt=$(podman mount dummy)
  cp -R ${mnt}/etc/foobar /tmp
  podman umount dummy
'

1.podman在内部使用buildah,它们也共享几乎相同的api

其他回答

另一个好的选择是首先构建容器,然后使用-c标志和shell解释器运行它,以执行一些命令

docker run --rm -i -v <host_path>:<container_path> <mydockerimage> /bin/sh -c "cp -r /tmp/homework/* <container_path>"

上述命令执行以下操作:

-i=以交互模式运行容器

--rm=执行后删除容器。

-v=将文件夹作为卷从主机路径共享到容器路径。

最后,/bin/sh-c允许您引入一个命令作为参数,该命令会将作业文件复制到容器路径。

我希望这个额外的答案可以帮助你

如果您没有正在运行的容器,只有一个图像,并且假设您只想复制一个文本文件,可以执行以下操作:

docker run the-image cat path/to/container/file.txt > path/to/host/file.txt

太长,读不下去了

$ docker run --rm -iv${PWD}:/host-volume my-image sh -s <<EOF
chown $(id -u):$(id -g) my-artifact.tar.xz
cp -a my-artifact.tar.xz /host-volume
EOF

描述

docker使用主机卷运行,chown工件,cp工件到主机卷:

$ docker build -t my-image - <<EOF
> FROM busybox
> WORKDIR /workdir
> RUN touch foo.txt bar.txt qux.txt
> EOF
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM busybox
 ---> 00f017a8c2a6
Step 2/3 : WORKDIR /workdir
 ---> Using cache
 ---> 36151d97f2c9
Step 3/3 : RUN touch foo.txt bar.txt qux.txt
 ---> Running in a657ed4f5cab
 ---> 4dd197569e44
Removing intermediate container a657ed4f5cab
Successfully built 4dd197569e44

$ docker run --rm -iv${PWD}:/host-volume my-image sh -s <<EOF
chown -v $(id -u):$(id -g) *.txt
cp -va *.txt /host-volume
EOF
changed ownership of '/host-volume/bar.txt' to 10335:11111
changed ownership of '/host-volume/qux.txt' to 10335:11111
changed ownership of '/host-volume/foo.txt' to 10335:11111
'bar.txt' -> '/host-volume/bar.txt'
'foo.txt' -> '/host-volume/foo.txt'
'qux.txt' -> '/host-volume/qux.txt'

$ ls -n
total 0
-rw-r--r-- 1 10335 11111 0 May  7 18:22 bar.txt
-rw-r--r-- 1 10335 11111 0 May  7 18:22 foo.txt
-rw-r--r-- 1 10335 11111 0 May  7 18:22 qux.txt

这个技巧之所以有效,是因为heredoc中的chown调用从正在运行的容器外部获取$(id-u):$(id-g)值;即docker主机。

好处是:

您不必在之前运行docker容器--name或docker容器create--name你不必在

docker cp[OPTIONS]CONTAINER:SRC_PATH DEST_PATH将从容器复制到主机。

例如docker cp测试:/opt/file1/etc/

对于Vice Versa:

docker cp[OPTIONS]SRC_PATH CONTAINER:DEST_PATH从主机复制到容器。

如果您需要一个小文件,可以使用此部分

Docker容器内部

docker运行-it-p 4122:4122<container_ID>

nc -l -p 4122 < Output.txt

主机

nc 127.0.0.1 4122 > Output.txt