wandadars
wandadars

Reputation: 1183

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/ && \

Upvotes: 21

Views: 19181

Answers (2)

BMitch
BMitch

Reputation: 264156

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.

Upvotes: 21

MatTheWhale
MatTheWhale

Reputation: 977

No, it is not.

RUN executes a bash command within the container being built. The chaining you refer to relies on the && operator, which is a bash operator that executes the left hand side command, but then only executes the right hand side command if the left hand side command was successful (returned with code 0).

You can only put bash commands in RUN and CMD/ENTRYPOINT. So unfortunately && will not work as an operator in COPY.

You'd just have to make four separate COPY statements instead.

Upvotes: 5

Related Questions