CodeBlanks Logo Icon CodeBlanks

COPY and ADD

Learn to copy files into an image with COPY.

COPY and ADD

COPY source destination copies files from the build context (usually the project folder) into the image. If the destination ends with / it is a directory; if WORKDIR is set, a relative path is resolved against it:

WORKDIR /app
COPY requirements.txt .        # /app/requirements.txt
COPY src/ ./src/               # copy a folder
COPY --chown=node:node . .     # set ownership

Why the dependency file first?

Copying the dependency list separately before the source code uses the cache well: when the code changes only the last layers are rebuilt, and the long package installation comes from the cache:

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt   # runs only when requirements change
COPY . .                                             # only this layer when the code changes

Practice Cache-friendly copying

Write a Dockerfile based on python:3.12-slim with WORKDIR /app: first copy requirements.txt, run pip install --no-cache-dir -r requirements.txt, then copy the whole project.

Starter code

terminal
# buraya yaz

Sample solution

terminal
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

Expected output

[+] Building 4.2s (8/8) FINISHED
 => naming to docker.io/library/api:latest done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does ADD do that COPY doesn't?

  • It only copies folders
  • It extracts local tar archives and can download from URLs Correct answer
  • It deletes files
  • It copies faster

Explanation: Because these "magic" behaviours cause surprises, COPY is preferred.

2 Set the owner of the copied files.

Question
COPY ____=node:node . .
Answer
COPY --chown=node:node . .

Explanation: --chown takes user:group.

3 Match.

Term Meaning
COPY Copies from the context
ADD Extracts tar, downloads URLs
COPY . . Copies the whole project
requirements.txt first Cache-friendly order

All lessons in Beginner