What is the difference between COPY and RUN in terms of Docker layers?
Why Interviewers Ask This
This tests whether you can apply Docker knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
Both COPY and RUN create new layers in the Docker image, but they affect caching and image size differently. COPY creates a layer containing the copied files. The cache for this layer is invalidated when the content of the copied files changes. If you COPY . /app and any file in the build context changes, all subsequent layers are rebuilt. Best practice: copy files that change rarely first, frequently-changed files last. RUN creates a layer containing the results of the command's filesystem changes. The cache is invalidated when the command string changes OR when a preceding layer's cache is invalidated. All files created and then deleted in separate RUN instructions are still in the image (in earlier layers). To actually reduce image size, combine creation and deletion in one RUN: RUN apt-get install -y curl && rm -rf /var/lib/apt/lists/* — the deletion and installation are in the same layer. Example of cache-friendly ordering: COPY package.json ./ (rarely changes) → RUN npm install (expensive, cached when package.json unchanged) → COPY src/ ./ (frequently changes, only invalidates from here). Never combine COPY . . before RUN npm install — every code change triggers reinstalling all packages.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last Docker project, I used this when...' immediately makes your answer more credible and memorable.