Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use cp command in dockerfile

I want to decrease the number of layers used in my Dockerfile.
So I want to combine the COPY commands in a RUN cp.

  • dependencies
    • folder1
    • file1
    • file2
  • Dockerfile

The following below commands work which I want to combine using a single RUN cp command

COPY ./dependencies/file1 /root/.m2

COPY ./dependencies/file2 /root/.sbt/

COPY ./dependencies/folder1 /root/.ivy2/cache

This following below command says No such file or directory present error. Where could I be going wrong ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

RUN cp ./dependencies/file1 /root/.m2 && \
    cp ./dependencies/file2 /root/.sbt/ && \
    cp ./dependencies/folder1 /root/.ivy2/cache

>Solution :

Problem

The COPY is used to copy files from your host to your container. So, when you run

COPY ./dependencies/file1 /root/.m2
COPY ./dependencies/file2 /root/.sbt/
COPY ./dependencies/folder1 /root/.ivy2/cache

Docker will look for file1, file2, and folder1 on your host.

However, when you do it with RUN, the commands are executed inside the container, and ./dependencies/file1 (and so on) does not exist in your container yet, which leads to file not found error.

In short, COPY and RUN are not interchangeable.


How to fix

If you don’t want to use multiple COPY commands, you can use one COPY to copy all files from your host to your container, then use the RUN command to move them to the proper location.

To avoid copying unnecessary files, use .dockerignore. For example:

.dockerignore

./dependencies/no-need-file
./dependencies/no-need-directory/

Dockerfile

COPY ./dependencies/ /root/
RUN mv ./dependencies/file1 /root/.m2 && \
    mv ./dependencies/file2 /root/.sbt/ && \
    mv ./dependencies/folder1 /root/.ivy2/cache
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading