Search code examples
dockerdockerfilemount

How to copy files from a docker image - dockerfile cmd


During build time, I want to copy a file from the image (from folder /opt/myApp/myFile.xml), to my host folder /opt/temp In the Dockerfile, I'm using the --mount as follows, trying to mount to my local test folder:

RUN --mount=target=/opt/temp,type=bind,source=test cp /opt/myApp/myFile.xml /opt/temp

I'm building the image successfully, but the local test folder is empty any ideas?


Solution

  • Copying files from the image to the host at build-time is not supported.
    This can easily be achieved during run-time using volumes.

    However, if you really want to work-around this by all means, you can have a look in the custom build outputs documentation, that introduced support for this kind of activity.

    Here is a simple example inspired from the official documentation:

    Dockerfile

    FROM alpine AS stage-a
    RUN mkdir -p /opt/temp/
    RUN touch /opt/temp/file-created-at-build-time
    RUN echo "Content added at build-time" > /opt/temp/file-created-at-build-time
    
    FROM scratch as custom-exporter
    COPY --from=stage-a /opt/temp/file-created-at-build-time .
    

    For this to work, you need to launch the build command using these arguments:

    DOCKER_BUILDKIT=1 docker build --output out .
    

    This will create on your host, aside the Dockerfile, a directory out with the file you need:

    .
    ├── Dockerfile
    └── out
        └── file-created-at-build-time
    
    cat out/file-created-at-build-time 
    Content added at build-time