ChatGPT解决这个技术问题 Extra ChatGPT

How to copy 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?

If you don't want to rebuild, why not "docker commit" ? That saves your image.
Just a remark on a notion nobody has addressed: in general, treat containers as "ephemeral". There ARE use cases to copy files into/from a running container (testing, prototyping). But if you find yourself in a position where you can't rebuild what you need using Dockerfiles and/or compose, then you may be in a bad place. You generally don't want to be backing up containers as if they were OS or even VM objects. Generally speaking :-)
@BerenddeBoer's link is now outdated, here's the new URL: docs.docker.com/engine/reference/commandline/commit

M
MikeiLL

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.


also note this can be on the host vm or main OS and works either host to container or vm to host (or main os)
In a Dockerfile you can use the ADD keyword to add files during build time.
@h3nrik COPY preferred over ADD when applicable.
use docker cp to copy from container to host works well, but when use it to copy files from host to container, no effect... anybody know why ? docker version: Docker version 1.10.3, build cb079f6-unsupported
Can i copy multiple files using docker cp from host to container?
P
Peter Mortensen

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

For me the host's mounting path didn't contain aufs but a devicemapper. Easiest way to check the containers mounting path (while it is running) is to run the command mount.
I tried the above solution. It copied the files into the docker specific directory. However, when I use bash for docker container, the files dont show up there. Is there something I am missing ?
The new path is /var/lib/docker/devicemapper/mnt/<>/rootfs/
For me, on Docker 1.4.1 (current latest), it's /var/lib/docker/aufs/diff/<id>/
what about for poor MacOS users? The mount directory is in /var/lib for me. find / -name docker was not helpful either.
M
Makan Tayebi

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

how can you run container? i thought you can do that only with an image.
I can't get it work when container is existing aka has run before. Tar below works nice.
The only way this worked for me was attaching the volume alongside running the image (instantiating the container). Ended up with: docker run -d -p -v /host/path:/mnt --name container_name image_name
This doesnt work for me. Atleast cannot run a container. Can run only image
I'm amazed that docker cp is a one-way operation!
Z
Zong

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

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

This works great! But don't forget to commit the change: docker commit `docker ps -l -q` ubuntu-with-file. Else the change will be lost (use whatever name you want instead of ubuntu-with-file)
In adition, we can use new docker exec feature to work with running container: docker exec -it <container_id> bash -c 'cat > /path/to/container/file' < /path/to/host/file/
@Mikl I think it should be docker exec -i ... instead of -it, because there's no TTY when piping in from a file.
If you are still stuck on an old version of Docker (as I am) and want to copy a whole directory, you could do this: tar -c -v -f - /path/to/host/directory | docker exec -i <container-name> bash -c 'tar -x -v --strip-components 1 -f - -C /path/to/container/directory'
Hmm, this did not work for me with Docker 19.03.8, host Centos 8, ubuntu:18.04 image. It did create file on the container, but it was blank.
A
Ali Hallaji

Typically there are three types:

From a container to the host docker cp container_id:./bar/foo.txt .

Also docker cp command works both ways too.

https://i.stack.imgur.com/qnhSi.jpg

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

https://i.stack.imgur.com/5GaiK.jpg

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

https://i.stack.imgur.com/pGr45.jpg


docker cp works both ways. No need to exec, cat, and redirect. docker cp host_file.txt container:/path/
And if the requirements is to copy more than just one file, tar comes pretty handy, something like the following: tar -czvf tmp.tar.gz *.* && docker exec -i container_id2 sh -c 'cat > ./bar/tmp.tar.gz && tar -xzvf tmp.tar.gz' < ./tmp.tar.gz
a
adean

If you need to do this on a running container you can use docker exec (added in 1.3).

First, find the container's name or ID:

$ docker ps
CONTAINER ID        IMAGE                        COMMAND             CREATED             STATUS              PORTS                   NAMES
b9b7400ddd8f        ubuntu:latest                "/bin/bash"         2 seconds ago       Up 2 seconds                                elated_hodgkin

In the example above we can either use b9b7400ddd8f or elated_hodgkin.

If you wanted to copy everything in /tmp/somefiles on the host to /var/www in the container:

$ cd /tmp/somefiles
$ tar -cv * | docker exec -i elated_hodgkin tar x -C /var/www

We can then exec /bin/bash in the container and verify it worked:

$ docker exec -it elated_hodgkin /bin/bash
root@b9b7400ddd8f:/# ls /var/www
file1  file2

Works great on on docker 1.16 on Centos 7.4 Great innovative idea.
K
Koray Tugay

Create a new dockerfile and use the existing image as your base. FROM myName/myImage:latest ADD myFile.py bin/myFile.py Then build the container: docker build .


This is what worked for me. NOTHING else. Thank you!
It will create a new image, not directly a new container. If you reuse this image while myFile.py as changed, it will use the older version of the file, unless you rebuild the image.
I find this the fastest way only if you're testing on a remote server.
According to this most people should use COPY rather than ADD. But for local files (as in this example) they're equivalent.
E
Eric Wilson

The solution is given below,

From the Docker shell,

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

From the host

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

The file shall be directly copied to the location where the container sits on the filesystem.


Great answer. In newer docker releases the path has been renamed to /var/lib/docker/aufs/mnt/
the devicemapper path doesn't seem to be work on fedora with docker 1.6. Have put it up as a separate Q, stackoverflow.com/questions/29939419/…, any comments would be appreciated.
The file /var/lib/docker does not exist....
C
Community

Another solution for copying files into a running container is using tar:

tar -c foo.sh | docker exec -i theDockerContainer /bin/tar -C /tmp -x

Copies the file foo.sh into /tmp of the container.

Edit: Remove reduntant -f, thanks to Maartens comment.


This is good if you need to send a whole directory. For a single file, Erik's answer is simpler.
@Kelvin: But tar also preserves file attributes and name. Amongst others that means you only have to type the name once (and there you get tab completion from your shell). So I'd say tar is actually simpler, as long as it is installed in the container.
The -f - is a bit redundant though, default behaviour is to write to stdout anyway.
this means there is a host dependency on tar
You are right - you need tar to be installed on the host and within the container. Nowadays using docker cp is the better solution.
C
Community

To copy a file from host to running container

docker exec -i $CONTAINER /bin/bash -c "cat > $CONTAINER_PATH" < $HOST_PATH

Based on Erik's answer and Mikl's and z0r's comments.


The accepted solutions sometimes disturbs the indentation of files when transferring to running containers. This works perfect for such cases
C
Community

This is a direct answer to the question 'Copying files from host to Docker container' raised in this question in the title.

Try docker cp. It is the easiest way to do that and works even on my Mac. Usage:

docker cp /root/some-file.txt some-docker-container:/root

This will copy the file some-file.txt in the directory /root on your host machine into the Docker container named some-docker-container into the directory /root. It is very close to the secure copy syntax. And as shown in the previous post, you can use it vice versa. I.e., you also copy files from the container to the host.

And before you downlink this post, please enter docker cp --help. Reading the documentation can be very helpful, sometimes...

If you don't like that way and you want data volumes in your already created and running container, then recreation is your only option today. See also How can I add a volume to an existing Docker container?.


a
aerin

I tried most of the (upvoted) solutions here but in docker 17.09 (in 2018) there is no longer /var/lib/docker/aufs folder.

This simple docker cp solved this task.

docker cp c:\path\to\local\file container_name:/path/to/target/dir/

How to get container_name?

 docker ps 

There is a NAMES section. Don't use aIMAGE.


P
Peter Mortensen

With Docker 1.8, docker cp is able to copy files from host to container. See the Docker blog post Announcing Docker 1.8: Content Trust, Toolbox, and Updates to Registry and Orchestration.


here is an example docker cp foo.txt mycontainer:/foo.txt
S
Sunny

To copy files/folders between a container and the local filesystem, type the command:

docker cp {SOURCE_FILE} {DESTINATION_CONTAINER_ID}:/{DESTINATION_PATH}

For example,

docker cp /home/foo container-id:/home/dir

To get the contianer id, type the given command:

docker ps

The above content is taken from docker.com.


F
Félix Adriyel Gagnon-Grenier

Assuming the container is already running, type the given command:

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

To share files using shared directory, run the container by typing the given command:

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

Note: Problems with permissions might arise as container's users are not the same as the host's users.


In addition: docker exec -it <container_id> bash -c 'cat > /path/to/container/file' < /path/to/host/file/
Note that cat will not be terminated once it exits. If it matters to you (if you are copying bash scripts, bash will refuse to run them), you should run lsof | grep yourfilename and kill the cat process that holds the said file.
Thx! Great tip. Can you pls tell me how to kill this process with one command? Something like kill $(lsof | grep /path/to/file | sed ...). I'll be grateful for your help
kill $(docker top CONTAINERNAME | sed -n '/cat$/p' | sed 's/^root[^0-9]\+\([0-9]\+\).*$/\1/')
S
Suraj Rao

This is the command to copy data from Docker to Host:

docker cp container_id:file path/filename /hostpath

docker cp a13fb9c9e674:/tmp/dgController.log /tmp/

Below is the command to copy data from host to docker:

docker cp a.txt ccfbeb35116b:/home/

S
Sunny

In a docker environment, all containers are found in the directory:

/var/lib/docker/aufs/required-docker-id/

To copy the source directory/file to any part of the container, type the given command:

sudo cp -r mydir/ /var/lib/docker/aufs/mnt/required-docker-id/mnt/


T
Tiago Martins Peres

Docker cp command is a handy utility that allows to copy files and folders between a container and the host system.

If you want to copy files from your host system to the container, you should use docker cp command like this:

docker cp host_source_path container:destination_path

List your running containers first using docker ps command:

abhishek@linuxhandbook:~$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              
  PORTS               NAMES
  8353c6f43fba        775349758637        "bash"              8 seconds ago       Up 7 
  seconds                            ubu_container

You need to know either the container ID or the container name. In my case, the docker container name is ubu_container. and the container ID is 8353c6f43fba.

If you want to verify that the files have been copied successfully, you can enter your container in the following manner and then use regular Linux commands:

docker exec -it ubu_container bash

Copy files from host system to docker container Copying with docker cp is similar to the copy command in Linux.

I am going to copy a file named a.py to the home/dir1 directory in the container.

docker cp a.py ubu_container:/home/dir1

If the file is successfully copied, you won’t see any output on the screen. If the destination path doesn’t exist, you would see an error:

abhishek@linuxhandbook:~$ sudo docker cp a.txt ubu_container:/home/dir2/subsub
        Error: No such container:path: ubu_container:/home/dir2

If the destination file already exists, it will be overwritten without any warning.

You may also use container ID instead of the container name:

docker cp a.py 8353c6f43fba:/home/dir1

T
Tiago Martins Peres

Container Up Syntax:

docker run -v /HOST/folder:/Container/floder 

In docker File

COPY hom* /myFolder/        # adds all files starting with "hom"
COPY hom?.txt /myFolder/    # ? is replaced with any single character, e.g., "home.txt"

P
Peter Mortensen

If the host is CentOS or Fedora, there is a proxy NOT in /var/lib/docker/aufs, but it is under /proc:

cp -r /home/user/mydata/* /proc/$(docker inspect --format "{{.State.Pid}}" <containerid>)/root

This cmd will copy all contents of data directory to / of container with id "containerid".


This is not unique to Redhat: it also works on Debian. (maybe all Gnu/Linux with /proc). Also extend path to put file somewhere else, not just root.
E
Everett Toews

tar and docker cp are a good combo for copying everything in a directory.

Create a data volume container

docker create --name dvc --volume /path/on/container cirros

To preserve the directory hierarchy

tar -c -C /path/on/local/machine . | docker cp - dvc:/path/on/container

Check your work

docker run --rm --volumes-from dvc cirros ls -al /path/on/container

i
ishandutta2007

In case it is not clear to someone like me what mycontainer in @h3nrik answer means, it is actually the container id. To copy a file WarpSquare.mp4 in /app/example_scenes/1440p60 from an exited docker container to current folder I used this.

docker cp `docker ps -q -l`:/app/example_scenes/1440p60/WarpSquare.mp4 .

where docker ps -q -l pulls up the container id of the last exited instance. In case it is not an exited container you can get it by docker container ls or docker ps


You can list ids of exited containers with docker ps -a or docker container ls -a.
M
Mourad MAMASSI
docker cp SRC_PATH CONTAINER_ID:DEST_PATH

For example, I want to copy my file xxxx/download/jenkins to tomcat

I start to get the id of the container Tomcat

docker ps

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
63686740b488        tomcat              "catalina.sh run"   12 seconds ago      Up 11 seconds       0.0.0.0:8080->8080/tcp   peaceful_babbage

docker cp xxxx/download/jenkins.war  63686740b488:usr/local/tomcat/webapps/

S
Syscall
docker cp [OPTIONS] SRC_PATH CONTAINER:DEST_PATH

The destination path must be pre-exist


P
Peter Mortensen

Many that find this question may actually have the problem of copying files into a Docker image while it is being created (I did).

In that case, you can use the COPY command in the Dockerfile that you use to create the image.

See the documentation.


k
karthik101

This is a onliner for copying a single file while running a tomcat container.

docker run -v /PATH_TO_WAR/sample.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat

This will copy the war file to webapps directory and get your app running in no time.


-v will mount (i.e. create a link), not copy
the difference in the result is that mounting hides the previous container content, e.g. if you mount a host folder on a container folder you cannot see anymore the previous container folder content
u
user3159411

My favorite method:

CONTAINERS:

CONTAINER_ID=$(docker ps | grep <string> | awk '{ print $1 }' | xargs docker inspect -f '{{.Id}}')

file.txt

mv -f file.txt /var/lib/docker/devicemapper/mnt/$CONTAINER_ID/rootfs/root/file.txt

or

mv -f file.txt /var/lib/docker/aufs/mnt/$CONTAINER_ID/rootfs/root/file.txt

the devicemapper path doesn't seem to be work on fedora with docker 1.6. Have put it up as a separate Q, stackoverflow.com/questions/29939419/…, any comments would be appreciated.
r
ryanyuyu

The best way for copying files to the container I found is mounting a directory on host using -v option of docker run command.


P
Peter Mortensen

There are good answers, but too specific. I find out docker ps is good way to get container id you're interested in. Then do

mount | grep <id>

to see where the volume is mounted. That's

/var/lib/docker/devicemapper/mnt/<id>/rootfs/

for me, but it might be a different path depending on the OS and configuration. Now simply copy files to that path.

Using -v is not always practical.


c
colin lamarre

I just started using docker to compile VLC, here's what you can do to copy files back and forth from containers:

su -
cd /var/lib/docker
ls -palR > /home/user/dockerfilelist.txt

Search for a familiar file in that txt and you'll have the folder, cd to it as root and voila! copy all you want.

There might be a path with "merged" in it, I guess you want the one with "diff" in it.

Also if you exit the container and want to be back where you left off:

docker ps -a
docker start -i containerid

I guess that's usefull when you didn't name anything with a command like

docker run -it registry.videolan.org:5000/vlc-debian-win64 /bin/bash

Sure the hacker method but so what!