1. The running container copy method
Use docker cp
the command to copy files from a physical machine to a running Docker container, or to copy files from a Docker container to a physical machine.
For example, to test.txt
copy into mycontainer
a container /app
directory , you can use the following command:
Copy files from host to container:
docker cp test.txt mycontainer:/app/test.txt
where test.txt
is the local file to copy, mycontainer
is the name of the container, and /app/test.txt
is the file path of the container.
If you want to copy the files in the Docker container to the physical machine, you can use the following command:
Copy files from the container to the host:
docker cp mycontainer:/app/test.txt test.txt
This command mycontainer
implements /app/test.txt
copying the files in the container to test.txt
the files .
Note that docker cp
the command requires Docker version 1.8 or later to work. In addition, you need to ensure that you have sufficient read and write permissions for the files to be copied.
2. Copy when building dockerfile
In the Dockerfile, you can directly use COPY
the or ADD
command to copy the local file to the image. The principle is that when Docker builds the image, it will first copy the local file to a temporary directory, and then add the directory to the file system of the image.
When using COPY
the or ADD
command, the Docker build engine will find the corresponding file or directory from the build context according to the specified source path, and copy it to the target path in the image. If the source path is a directory, the destination path must /
end with , or the COPY or ADD operation will fail.
For example, in the following Dockerfile:
FROM nginx:latest
COPY index.html /usr/share/nginx/html/
ADD static.tar.gz /usr/share/nginx/html/
This Dockerfile specifies nginx:latest
as the base image, and then index.html
copies the files in the local directory to /usr/share/nginx/html/
the directory . When building an image, the Docker build engine will first index.html
copy to a temporary directory, and then add the directory to the image's file system, so as to copy files from the local to the image.
Therefore, it is possible to copy local files into the container directly using the COPY
or . ADD
Moreover, doing so also automates the copying of files into the image, so that the image can be used directly when creating a new container, and there is no need to manually copy the files.