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

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

问题描述:

我正在尝试为我们使用的Docker容器构建备份和还原解决方案。

I am trying to build a backup and restore solution for the Docker containers that we work with.

我已经创建了Docker基本映像, ubuntu:base ,并且不想每次都使用Docker文件重建它来向其添加文件。

I have Docker base image that I have created, ubuntu:base, and do not want have to rebuild it each time with a Docker file to add files to it.

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

I want to create a script that runs from the host machine and creates a new container using the ubuntu:base Docker image and then copies files into that container.

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

How can I copy files from the host to the container?

cp 命令可用于复制文件。

The cp command can be used to copy files.

可以将一个特定文件复制到容器中,例如:

One specific file can be copied TO the container like:

docker cp foo.txt mycontainer:/foo.txt

可以从容器中复制一个特定文件,例如:

One specific file can be copied FROM the container like:

docker cp mycontainer:/foo.txt foo.txt

为了强调起见, mycontainer 容器 ID,不是一个图像 ID。

For emphasis, mycontainer is a container ID, not an image ID.

文件夹 src 包含的多个文件可以是使用以下命令复制到 target 文件夹中:

Multiple files contained by the folder src can be copied into the target folder using:

docker cp src/. mycontainer:/target
docker cp mycontainer:/src/. target

参考:用于 cp

在1.8之前的Docker版本中,只能将文件从容器复制到主机。不是从主机到容器。

In Docker versions prior to 1.8 it was only possible to copy files from a container to the host. Not from the host to a container.