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

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

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

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


当前回答

答案很好,但过于具体。我发现docker ps是获取您感兴趣的容器id的好方法

mount | grep <id>

查看卷的安装位置。那是

/var/lib/docker/devicemapper/mnt/<id>/rootfs/

对我来说,但这可能是一条不同的路径,具体取决于操作系统和配置。现在只需将文件复制到该路径。

使用-v并不总是实用的。

其他回答

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

{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

您可以使用

ifconfig

然后只需输入Docker容器并键入

scp user_name@ip_address:/path_to_the_file destination

在任何情况下,如果您没有安装SSH客户端和服务器,只需使用以下方法进行安装:

sudo apt-get install openssh-server

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

将点文件放入shell会话(使用base64转义)

有时,对shell启动执行单独的交互式命令会很麻烦。当我想将一个点文件复制到我的容器中,这样我的shell就会包含我的自定义项

docker exec -u root -it mycontainername bash -c "echo "$(cat ~/.bashrc | base64 -w 0)" | base64 --decode > /tmp/.bashrc_inside_container; bash --rcfile /tmp/.bashrc_inside_container"

这就是对我有用的

#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