Can Docker COPY commands be chained
Asked Answered
B

3

20

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/ && \
Butanol answered 11/8, 2017 at 20:46 Comment(0)
E
20

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.

Eradis answered 11/8, 2017 at 21:34 Comment(0)
U
5

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.

Underlet answered 11/8, 2017 at 21:15 Comment(0)
L
0

Following the BMitch's suggested approach, I like to copy all the files that i need from my project folder

COPY local_path/app/ /src/app/

And all the files that I dont want to copy i put into a ./.dockerignore file. Example to a Python project:

# Project
...

# Python Byte-compiled / optimized / DLL files
__pycache__/
*.pyc
*.pyo
*.pyd

# Environments
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
Lissie answered 12/8 at 18:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.