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

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

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

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


当前回答

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

实现这一点的最简单的方法是,

查找容器iddocker cp<文件名><容器id>:<路径>

创建一个新的dockerfile并使用现有图像作为基础。FROM myName/myImage:最新添加myFile.py bin/myFile.py然后构建容器:码头建造。

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

# 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 run -d -v /blah1/blah2:/mnt --name mntcontainer ubuntu /bin/sh -c "while true; do echo hello world; sleep 1; done"

then

docker exec -it mntcontainer bash