Can i copy files from host to container and from container to host ? If so, how can i do it ?

  • Yes, you can copy files from host to container and from container to host.
  • The docker cp utility copies the contents of source to the destination.
  • You can copy from the containerโ€™s file system to the local machine or the reverse, from the local filesystem to the container.
  • Localhost –> Container
    • docker cp <path of local host> containerid:<path of container>
  • Container –> Localhost
    • docker cp containerid:<path of container> <path of local host>

  • Let us see this in action by this simple example of running a docker image of an Apache HTTP Server.
  • I have a simple index.html page, which i will copy to the /usr/local/apache2/htdocs/ path of HTTP Server.
  • Contents of index.html
<!doctype html>
<html>
  <head>
    <title>Docker cp utility</title>
  </head>
  <body>
    <p>This is a simple web page <strong>Use strong tag to appear bold</strong> , just like this <strong>p</strong> tag and its contents.</p>
  </body>
</html>
  • Dockerfile
FROM httpd:2.4
COPY website/ /usr/local/apache2/htdocs/
  • i have index.html in the website folder. This is how my directory structure looks
  • Let us now issue the command to run the container docker build -t apache-docker-example .
  • Once the container starts, you can visit the web page on a browser by typing : http://localhost
  • Next let us make a change to the index.html in our local by adding a span tag
<!doctype html>
<html>
  <head>
    <title>Docker cp utility</title>
  </head>
  <body>
    <p>This is a simple web page <strong><span style="color: red">Use strong tag to appear bold</span></strong> , just like this <strong>p</strong> tag and its contents.</p>
  </body>
</html>
  • To copy this file from the host to the container, first get the container id
  • Now run the command : docker cp website/index.html 69a71ef9197a:/usr/local/apache2/htdocs/
  • If you refresh the webpage, you will see that the changes have been copied and webpage looks like this
  • Next, let us copy contents from the container to the host. We will copy the logs folder from Apache server to local host.
  • docker cp 69a71ef9197a:/usr/local/apache2/logs /Users/rajeshp/docker/apache
  • After the above command , if you look at the path , you will see the log folder have been copied from container to host

Thank you !!

2 thoughts on “Can i copy files from host to container and from container to host ? If so, how can i do it ?

Leave a Reply