Dockerfile Directives

COPY vs ADD in Dockerfile: Which Should You Use?

Best practices for copying files into Docker images. Why COPY is almost always preferred over ADD.

Quick Docker Solution
Safe CommandBeginner
COPY package.json package-lock.json ./
When to use this scenario:You are optimizing Dockerfile build caching and deciding whether to use COPY or ADD for your source code and archives.

Step-by-Step Execution Guide

1Standard file and directory copy (Preferred)
COPY src/ /app/src/

COPY only performs straightforward local file copying from host context into the image layer.

2Automatic tar archive extraction with ADD
ADD archive.tar.gz /opt/

ADD automatically unpacks recognized compressed tar archives (gzip, bzip2, xz) into the destination directory.

3Copy with ownership permissions
COPY --chown=node:node . /app

Sets file user and group ownership during copy without requiring a separate "RUN chown -R" layer.

Critical Docker Pitfalls & Precautions

  • β€’Do not use "ADD <remote-url>". It is better practice to use "RUN curl -fsSL <url> | tar -xz" to avoid leaving uncompressed cache files in image layers.
Frequently Asked Questions

COPY vs ADD Differences - Frequently Asked Questions

Common questions about container isolation, signal handling, and runtime behavior.

COPY is transparent and predictable. ADD has implicit behaviors (tar extraction, remote URL fetching) that can introduce security risks and unexpected build errors.