DEV Community

Devtonight
Devtonight

Posted on • Updated on • Originally published at devtonight.com

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
docker run -it --rm nginx ls -al /etc/nginx
Enter fullscreen mode Exit fullscreen mode

Now you will be able to see and copy the required file in the list.

Feel free to visit devtonight.com for more related content.

Top comments (0)