Search code examples
linuxdockerdockerfile

How to copy files from dockerfile to host?


I want to get some files when dockerfile built successfully, but it doesn't copy files from container to host.

That means when I have built dockerfile, the files already be host.


Solution

  • Copying files "from the Dockerfile" to the host is not supported. The Dockerfile is just a recipe specifying how to build an image.

    When you build, you have the opportunity to copy files from host to the image you are building (with the COPY directive or ADD)

    You can also copy files from a container (an image that has been docker run'd) to the host with docker cp (atually, the cp can copy from the host to the container as well)

    If you want to get back to your host some files that might have been generated during the build (like for example calling a script that generates ssl), you can run a container, mounting a folder from your host and executing cp commands.

    See for example this getcrt script.

    docker run -u root --entrypoint=/bin/sh --rm -i -v ${HOME}/b2d/apache:/apache apache << COMMANDS
    pwd
    cp crt /apache
    cp key /apache
    echo Changing owner from \$(id -u):\$(id -g) to $(id -u):$(id -u)
    chown -R $(id -u):$(id -u) /apache/crt
    chown -R $(id -u):$(id -u) /apache/key
    COMMANDS
    

    Everything between COMMANDS are commands executed on the container, including cp ones which are copying on the host ${HOME}/b2d/apache folder, mounted within the container as /apache with -v ${HOME}/b2d/apache:/apache.

    That means each time you copy anything on /apache in the container, you are actually copying in ${HOME}/b2d/apache on the host!