How to copy files from host to Docker container?

ID : 433

viewed : 169

Tags : dockerdocker-containerdocker





Top 5 Answer for How to copy files from host to Docker container?

vote vote

94

The cp command can be used to copy files.

One specific file can be copied TO the container like:

docker cp foo.txt container_id:/foo.txt 

One specific file can be copied FROM the container like:

docker cp container_id:/foo.txt foo.txt 

For emphasis, container_id is a container ID, not an image ID. (Use docker ps to view listing which includes container_ids.)

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

docker cp src/. container_id:/target docker cp container_id:/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.

vote vote

87

  1. Get container name or short container id:

    $ docker ps 
  2. Get full container id:

    $ docker inspect -f   '{{.Id}}'  SHORT_CONTAINER_ID-or-CONTAINER_NAME 
  3. 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 
vote vote

70

The cleanest way is to mount a host directory on the container when starting the container:

{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 
vote vote

63

The following is a fairly ugly way of doing it but it works.

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

60

Typically there are three types:

  1. From a container to the host

    docker cp container_id:./bar/foo.txt . 

dev1

  1. From the host to a container

    docker exec -i container_id sh -c 'cat > ./bar/foo.txt' < ./foo.txt 
  2. Second approach to copy from host to container:

    docker cp foo.txt mycontainer:/foo.txt 

dev2

  1. From a container to a container mixes 1 and 2

    docker cp container_id1:./bar/foo.txt .  docker exec -i container_id2 sh -c 'cat > ./bar/foo.txt' < ./foo.txt 

dev3

Top 3 video Explaining How to copy files from host to Docker container?







Related QUESTION?