ADD or COPY in Dockerfile

Concept & fundamental

ADD and COPY are functionally similar
    ADD has some features like local-only tar extraction and remote URL support
    Consequently, the best use for ADD is local tar file auto-extraction into the image, as in
    1
    ADD rootfs.tar.xz /.
    Copied!
    COPY only supports the basic copying of local files into the container
    With multiple steps in Dockerfile, that use different files from your context --> COPY them individually, rather than all at once. This will ensure that each step’s build cache is only invalidated (forcing the step to be re-run) if the specifically required files change.
    1
    COPY requirements.txt /tmp/
    2
    RUN pip install --requirement /tmp/requirements.txt
    3
    COPY . /tmp/
    Copied!
    Results in fewer cache invalidations for the RUN step, than if you put the COPY . /tmp/ before it.
Because image size matters, using ADD to fetch packages from remote URLs is strongly discouraged; you should use curl or wget instead. That way you can delete the files you no longer need after they’ve been extracted and you won’t have to add another layer in your image.
For example, you should avoid doing things like:
1
ADD http://example.com/big.tar.xz /usr/src/things/
2
RUN tar -xJf /usr/src/things/big.tar.xz -C /usr/src/things
3
RUN make -C /usr/src/things all
Copied!
And instead, do something like ⭐️ :
1
RUN mkdir -p /usr/src/things \
2
&& curl -SL http://example.com/big.tar.xz \
3
| tar -xJC /usr/src/things \
4
&& make -C /usr/src/things all
Copied!
For other items (files, directories) that do not require ADD’s tar auto-extraction capability
You should always use COPY.

Reference:

Last modified 2yr ago