Details the method of copying data between the Docker container and the Docker container

  • 2020-06-07 05:44:57
  • OfStack

How do I copy data to each other inside and outside the Docker container?

Copy files from the container to the host


docker cp <containerId>:/file/path/within/container /host/path/target

Copy files from the host to the container

1. Mount the host data volume into the container with -ES11en


docker run -v /path/to/hostdir:/mnt $container 

Copy in the container


cp /mnt/sourcefile /path/to/destfile 

2. Copy directly to the container physical storage system on the host

A. Gets the container name or id:


$ docker ps 

B. Gets id for the entire container


$ docker inspect -f '{{.Id}}'  steps A Gets the name or id 

C. Copy file on host:


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

or


$ sudo cp path-file-host /var/lib/docker/devicemapper/mnt/123abc<<id>>/rootfs/root

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 

3. Use I/O


docker run -i ubuntu /bin/bash -c 'cat > /path/to/container/file' < /path/to/host/file/

or


docker exec -it <container_id> bash -c 'cat > /path/to/container/file' < /path/to/host/file/


Related articles: