SIGN IN
    As we have seen in previous articles, Docker can make it easy to deploy and run applications.

    But sometimes you need to send files from the host machine to the Docker container, and from the container to the host.

    In this article we can see how to do it.

    The commands below assume that you already have Docker installed. If not, then you can find out how to do it in this or this article.

    To copy to and from Docker, we will use the docker cp utility.

    The docker cp utility copies the contents of the source to the destination.

    You can copy from the container's file system to the local computer, or vice versa, from the local file system to the container.


    Example: Localhost -> Container
    docker cp <path to file on host machine> containerid:<path to file in container>
    

    Example: Container -> Localhost
    docker cp containerid:<path to file on host machine> <path to file on host machine>
    


    Let's see this in action with a simple Nginx docker image example.

    We can use the following command:

    docker run -d --name nginx_copy nginx
    

    where:
    nginx_copy - container name (you can use any)
    nginx - name of the image on the docker hub that we will use

    If you do not have this container on the server, we wait until it is downloaded.


    Now let's go into the container to see / find out where or which file to copy.

    docker exec -it nginx_copy /bin/bash
    

    Now we will display the contents of the /etc/nginx folder in the terminal

    ls -la /etc/nginx/
    

    For example, we need to copy the nginx.conf configuration file and we know that it is located along the /etc/nginx/nginx.conf path. To do this, enter the following command:

    docker cp nginx_copy:/etc/nginx/nginx.conf ~/nginx.conf
    

    Where:

    nginx_copy - the container from which we are copying;
    /etc/nginx/nginx.conf - path to the file to be copied;
    ~/nginx.conf - destination and file name (you can set another file name)

    Now let's look at the result:

    ls -la


    As you can see, the file was successfully copied to the host. Now we can change it, then upload it back.

    Consider how to copy a file to a container.

    Suppose we now need to copy the modified nginx.conf file back into the container. To do this, we can use this construction:

    docker cp ~/nginx.conf nginx_copy:/etc/nginx/nginx.conf_cp
    

    If everything is entered correctly, we will be able to observe this file in the container.

    Let's go to the container:

    docker exec -it nginx_copy /bin/bash
    

    And list the /etc/nginx directory:

    ls -la


    As we can see the new file is copied inside the container.

    By the same principle, you can transfer data from the container to the host and vice versa.