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 ?
RUN cp ./dependencies/file1 /root/.m2 &&
cp ./dependencies/file2 /root/.sbt/ &&
cp ./dependencies/folder1 /root/.ivy2/cache
3
Answers
You a re missing final slash in
/root/.ivy2/cache/
You can’t do that.
COPY
copies from the host to the image.RUN cp
copies from a location in the image to another location in the image.To get it all into a single COPY statement, you can create the file structure you want on the host and then use
tar
to make it a single file. Then when youCOPY
orADD
that tar file, Docker will unpack it and put the files in the correct place. But with the current structure your files have on the host, it’s not possible to do in a single COPY command.Problem
The COPY is used to copy files from your host to your container. So, when you run
Docker will look for
file1
,file2
, andfolder1
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 tofile not found
error.In short,
COPY
andRUN
are not interchangeable.How to fix
If you don’t want to use multiple
COPY
commands, you can use oneCOPY
to copy all files from your host to your container, then use theRUN
command to move them to the proper location.To avoid copying unnecessary files, use .dockerignore. For example:
.dockerignore
Dockerfile