What is the difference between ADD and COPY in Dockerfile?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Docker development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
Both ADD and COPY copy files from the build context (your local machine) into the Docker image. COPY is the simpler, preferred choice for most use cases: COPY source destination — copies files/directories from the build context into the image. It is explicit and predictable — no hidden behaviors. Examples: COPY package.json /app/; COPY src/ /app/src/. ADD has two additional capabilities beyond COPY: (1) URL support: ADD https://example.com/file.tar.gz /tmp/ — downloads from a URL (but this creates a layer without caching benefits; use curl/wget in RUN instead for better control); (2) Auto-extraction: if the source is a local tar archive (gz, bz2, xz), ADD automatically extracts it into the destination directory — ADD myapp.tar.gz /app/ extracts the contents. Best practices: use COPY by default — its behavior is transparent and predictable. Use ADD only when you specifically need its auto-extraction feature. The Docker documentation explicitly recommends preferring COPY over ADD for clarity.
Pro Tip
This topic has Docker-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.