Search code examples
dockerdockerfileconcatenationappend

Dockerfile: Append/concat to a file from a temporary source


How can I append/concat a source file, say "myfile", to another file in the target container, without storing the source file in the final docker image? That is, using the source file only temporarily.

Is there an APPEND-like Dockerfile instruction?


Solution

  • An APPEND-like instruction for Dockerfile(s) does not exist.

    As of to date, a RUN bind mount is the most efficient way to temporarily-only use a source file in the build context, i.e. without keeping it in the final image. With this, you only need one RUN instruction, thus creating a single cache layer in the Docker image.

    For example, to append a temporary source file, do something like:

    RUN --mount=type=bind,source=myfile,target=/tmp/myfile \
        cat /tmp/myfile >> /some/path
    

    Note: the --mount option requires BuildKit.


    The alternative of first COPY'ing a temporary file to only removing it later explicitly in a RUN instruction of course works, but that would create 2 cache layers in the Docker image:

    COPY myfile /tmp/myfile
    RUN cat /tmp/myfile >> /some/path && rm /tmp/myfile