Aman .sinha
Aman .sinha

Reputation: 53

Dockerfile- Reduce layers by Copying in a single statement

Currently, In my dockerfile i am using multiple COPY commands to copy directories from my repository.

How can i achieve the same results as above using a single COPY command. Is there a way?

Upvotes: 2

Views: 3748

Answers (2)

atline
atline

Reputation: 31664

If you just want to copy things to the same folder /opt, maybe simply using next:

Folder structure:

.
├── conftest.py
├── Dockerfile
├── .dockerignore
├── goss
├── newman
├── requirements.txt
├── templates
└── validation

Dockerfile:

FROM alpine
COPY . /opt
#RUN mv /opt/conftest.py /opt/validation
RUN ls /opt

.dockerignore:

Dockerfile

Execution:

$ docker build -t abc:1 . --no-cache
Sending build context to Docker daemon  6.144kB
Step 1/3 : FROM alpine
 ---> 28f6e2705743
Step 2/3 : COPY . /opt
 ---> 8beb53be958c
Step 3/3 : RUN ls /opt
 ---> Running in cfc9228124fb
conftest.py
goss
newman
requirements.txt
templates
validation
Removing intermediate container cfc9228124fb
 ---> 4cdb9275d6f4
Successfully built 4cdb9275d6f4
Successfully tagged abc:1

Here, we use COPY . /opt to copy all things in current folder to /opt/ of container. We use .dockerignore to ignore the files/folders which won't want to copy to containers.

Additional, not sure the rules for COPY conftest.py /opt/validation/conftest.py correct or not, if it's correct, you may have to use RUN mv to move it to specified folder.

Upvotes: 1

anemyte
anemyte

Reputation: 20286

There is a little hack with the scratch image:

FROM scratch as tmp

COPY foo /opt/some/path/foo
COPY bar /usr/share/tmp/bar

FROM debian:buster

COPY --from=tmp / /

CMD bash -c "ls /opt/some/path /usr/share/tmp"
❯ docker build -t test . && docker run --rm test
/opt/some/path:
foo

/usr/share/tmp:
bar

scratch is a pseudo-image, it is much like an empty directory. The hack is to copy everything there as it should be in the final image, then merge root directories. The merge produces a single layer.

❯ docker inspect --format '{{.RootFS}}' test
{layers [ 
 sha256:c2ddc1bc2645ab5d982c60434d8bbc6aecee1bd4e8eee0df7fd08c96df2d58bb
 sha256:fd35279adf8471b9a168ec75e3ef830046d0d7944fe11570eef4d09e0edde936
] }

Upvotes: 7

Related Questions