Copying files from host to Docker container

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

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 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?


The cp command can be used to copy files. One specific file can be copied like:

docker cp foo.txt mycontainer:/foo.txt
docker cp mycontainer:/foo.txt foo.txt

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

Reference: Docker CLI docs for cp

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.


  • Get container name or short container id:

    $ docker ps
    
  • Get full container id:

    $ docker inspect -f   '{{.Id}}'  SHORT_CONTAINER_ID-or-CONTAINER_NAME
    
  • Copy file:

    $ sudo cp path-file-host /var/lib/docker/aufs/mnt/FULL_CONTAINER_ID/PATH-NEW-FILE
    
  • EXAMPLE:

    $ docker ps
    
    CONTAINER ID      IMAGE    COMMAND       CREATED      STATUS       PORTS        NAMES
    
    d8e703d7e303   solidleon/ssh:latest      /usr/sbin/sshd -D                      cranky_pare
    
    $ docker inspect -f   '{{.Id}}' cranky_pare
    

    or

    $ docker inspect -f   '{{.Id}}' d8e703d7e303
    
    d8e703d7e3039a6df6d01bd7fb58d1882e592a85059eb16c4b83cf91847f88e5
    
    $ sudo cp file.txt /var/lib/docker/aufs/mnt/**d8e703d7e3039a6df6d01bd7fb58d1882e592a85059eb16c4b83cf91847f88e5**/root/file.txt
    

    最简洁的方法是在运行命令之前在容器上安装主机目录:

    {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
    
    链接地址: http://www.djcxy.com/p/3010.html

    上一篇: 如何在不通过存储库的情况下将Docker镜像从一台主机复制到另一台主机?

    下一篇: 将文件从主机复制到Docker容器