Search code examples
dockerdockerfile

Can Docker COPY commands be chained


Is is possible to chain the COPY commands together like what can be done with the RUN command?

Example of chaining run command:

RUN echo "root:user_2017" | chpasswd && \
    groupadd -g 1000 user && \
    useradd -u 1000 -m -s /bin/bash user && \
    passwd -d user

Would something like what is shown below prevent the introduction of multiple intermediate images if I had to perform many copies from the host to the image? I know what is shown below won't work because each line needs to be a separate command when the && is used to tie multiple lines together.

COPY ./folder1A/* /home/user/folder1B/ && \
     ./folder2A/* /home/user/folder2B/ && \
     ./folder3A/* /home/user/folder3B/ && \
     ./folder4A/* /home/user/folder4B/ && \

Solution

  • Since COPY commands cannot be chained, it's typically best to structure your context (directories you are copying from) in a way that is friendly to copy into the image.

    So instead of:

    COPY ./folder1A/* /home/user/folder1B/ && \
         ./folder2A/* /home/user/folder2B/ && \
         ./folder3A/* /home/user/folder3B/ && \
         ./folder4A/* /home/user/folder4B/ && \
    

    Place those folders into a common directory and run:

    COPY user/ /home/user/
    

    If you are copying files, you can copy multiple into a single target:

    COPY file1.zip file2.txt file3.cfg /target/app/
    

    If you try to do this with a directory, you'll find that docker flattens it by one level, hence the suggestion to reorganize your directories into a common parent folder.