How to Copy Files Quickly in Docker Images to Host
Sometimes, there are situations where we just need to copy one or two files in the original Docker images to the host PC. For example, when we build Docker-based LAMP/LEMP stacks, we keep web server configuration files and database configuration files externally. Then we make necessary modifications and copy them back while building the final image.
Let’s assume that we wanted to copy the nginx.conf
file in the Nginx web server Docker image into our PC. For that, first, we need to pull that image.
docker pull nginx
After that, if we clearly know the exact path and the file name, we can mention it like this. What it does is, it create a temporary Docker container using the nginx
image. Then it prints the contents of the required file using the cat
(concatenate) command.
docker run -it --rm nginx cat /etc/nginx/nginx.conf
Instead of printing the content of the file in the terminal, we can even put them into a file like this.
docker run -it --rm nginx cat /etc/nginx/nginx.conf > nginx.conf
Bonus: What If You Cannot Remember The Exact Path?
Well, that is possible. We already used the cat
command, likewise, we can also use the ls
command the same way to list files. The following command will display the files and directories in the root directory of the Nginx Docker image.
docker run -it --rm nginx ls -al
Then you can find the path to the file by using the ls
command again and again.
docker run -it --rm nginx ls -al /etc
docker run -it --rm nginx ls -al /etc/nginx
Now you will be able to see and copy the required file in the list.