Docker Interview Question 8: .dockerignore Build Context
Docker Interview Questions · Test 1 · question 8 of 10
A repository root contains the Dockerfile, the source, a 1.5 GB node_modules directory, the .git directory, and a .env file with API keys. The Dockerfile uses COPY . ., and the build is run with docker build .. Builds spend a long time on "transferring context", and a security review finds .env inside the published image. What is the best fix for both problems?
Show answer and explanation
Answer:
docker build . sends the whole directory as the build context. A .dockerignore file in the root of the context excludes matching files and directories from the context, which avoids sending unwanted files to the builder and speeds up the build. Because excluded files never reach the builder, COPY . . cannot copy .env into a layer.
Option A deletes the files in a *later* layer. The full context is still transferred, and the COPY layer that contains .env is still part of the image, so the secret can still be recovered.
Option C changes only where the Dockerfile lives. The context is still ., the repository root, so the same files are sent and copied.
Option D rebuilds every layer from scratch, but the context and the COPY . . instruction are unchanged. The build is slower and .env is still copied in.
Reference: Build context - .dockerignore files