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

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

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

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


当前回答

许多发现这个问题的人实际上可能会在创建Docker映像时遇到将文件复制到Docker映像中的问题(我确实这样做了)。

在这种情况下,您可以使用Dockerfile中的COPY命令来创建图像。

请参阅文档。

其他回答

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

{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 1.8,Docker cp能够将文件从主机复制到容器。请参阅Docker博客文章Announcing Docker 1.8:内容信任、工具箱以及注册表和编排更新。

您可以使用以下命令

将文件从主机复制到docker容器docker cp/主机文件container_id:/to_the_place_you_want_the_file_to_be将文件从docker容器复制到主机docker cp container_id:src_path to_the_place_you_want_the_file_to_be

我希望在没有.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。

这就是对我有用的

#Run the docker image in detached mode 
$docker run -it -d test:latest bash

$ docker ps
CONTAINER ID        IMAGE               COMMAND
a6c1ff6348f4        test:latest     "bash"

#Copy file from host to container
sudo docker cp file.txt a6c1ff6348f4:/tmp

#Copy the file from container to host
docker cp test:/tmp/file.txt /home