我正在尝试为我们使用的Docker容器构建一个备份和恢复解决方案。

我有一个我创建的Docker基础镜像ubuntu:base,不想每次都用Docker文件重新构建它来添加文件。

我想创建一个从主机运行的脚本,并使用ubuntu:base Docker映像创建一个新容器,然后将文件复制到该容器中。

如何将文件从主机复制到容器?


当前回答

最干净的方法是在启动容器时在容器上装载主机目录:

{host} docker run -v /path/to/hostdir:/mnt --name my_container my_image
{host} docker exec -it my_container bash
{container} cp /mnt/sourcefile /path/to/destfile

其他回答

将文件从主机复制到正在运行的容器

docker exec -i $CONTAINER /bin/bash -c "cat > $CONTAINER_PATH" < $HOST_PATH

根据Erik的回答以及Mikl和z0r的评论。

我只需从主机上直接复制容器所在位置的文件。

例如:

首先查找容器id:

root@**3aed62678d54**:/home#

然后在主机上,假设文件位于主目录中:

root@saasdock:/home/dnepangue# cp cheering_nasa.gif /var/lib/docker/aufs/mnt/**3aed62678d54**a5df47a4a00a58bb0312009c2902f8a37498a1427052e8ac454b/home/

返回容器。。。

root@**3aed62678d54**:/home# ls cheering_nasa.gif

以下是一种相当丑陋的方法,但它确实有效。

docker run -i ubuntu /bin/bash -c 'cat > file' < file

我希望在没有.git文件夹等文件的容器中进行构建过程,但我希望在交互式运行容器以调试问题时使用这些文件。与Ben Davis的答案一样,这将在容器中执行文件副本。但当我进入容器时,我不想亲自运行该命令。因此,以下脚本将完成此任务:

# mount the current [project] directory as read only
docker run --name my_container -v $(pwd):/mnt/application:ro -itd my_image /bin/bash
# copy the missing project files from the mounted directory
docker exec -it my_container /bin/bash -c 'cp -rnT /mnt/application $HOME/application'
# interactively use the container
docker attach my_container

这将留下my_container容器实例。要再次运行该命令,必须编写docker rm my_container。或者,如果您想再次进入该容器实例,可以执行docker start my_container和docker attach my_containr。

请注意cp-n标志,如果目标中已经存在文件,它将防止覆盖这些文件。:ro部分不允许更改主机文件。您可以将$(pwd)更改为特定目录,如/home/user/dev/application。

容器向上语法:

docker run -v /HOST/folder:/Container/floder 

在docker文件中

COPY hom* /myFolder/        # adds all files starting with "hom"
COPY hom?.txt /myFolder/    # ? is replaced with any single character, e.g., "home.txt"