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

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

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

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


当前回答

假设容器已经在运行,请键入给定的命令:

# cat /path/to/host/file/ | docker exec -i -t <container_id> bash -c "/bin/cat > /path/to/container/file"

要使用共享目录共享文件,请键入以下命令运行容器:

# docker run -v /path/to/host/dir:/path/to/container/dir ...

注意:由于容器的用户与主机的用户不同,因此可能会出现权限问题。

其他回答

从容器复制到主机目录

docker cp [container-name/id]:./app/[index.js] index.js

(假设您在dockerfile中创建了一个workdir/app)

从主机复制到容器

docker cp index.js [container-name/id]:./app/index.js

如果您能够使用容器注册表,appendlayer Python包将满足您的要求:

假设ubuntu:base在注册表中已经可用。

然后,您可以使用脚本在上面添加一个由一些本地文件组成的新层,将整个层保存为新图像(即ubuntu:test)。

$ pip install appendlayer
$ tar cvf - test.txt | appendlayer <host> <repository> <old-tag> <new-tag>

所有这些都无需重建或甚至将任何图像数据下载到本地计算机。

将点文件放入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"

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

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

解决方案如下所示,

从Docker外壳,

root@123abc:/root#  <-- get the container ID

来自主机

cp thefile.txt /var/lib/docker/devicemapper/mnt/123abc<bunch-o-hex>/rootfs/root

文件应直接复制到文件系统中容器所在的位置。