DevNet Associate (DEVASC) v1.0Application Deployment and SecurityMedium

A team is developing a microservice that runs in a Docker container and needs to access a database. During development, they frequently rebuild the container image. To optimize rebuild times and reduce the final image size, while also improving security by limiting the attack surface, which Dockerfile feature should be utilized?

  1. AAlways using `apt-get update` without `apt-get clean`.
  2. BUsing `ADD` instruction instead of `COPY`.
  3. CSetting the `WORKDIR` to `/tmp`.
  4. DImplementing a multi-stage build.
Show answer & explanation

Correct answer: D. Implementing a multi-stage build.

Multi-stage builds allow you to use multiple `FROM` statements in a single Dockerfile. You can use an initial stage to compile code and install build dependencies, and then copy only the necessary artifacts into a much smaller, final image. This significantly reduces image size, build times, and the attack surface by excluding build tools and unnecessary files.

Why the other options are wrong

  • A. Not cleaning `apt-get` caches actually *increases* image size and doesn't improve rebuild times; it's a bad practice for optimization.
  • B. `ADD` has extra features (like remote URLs, tar extraction) but doesn't inherently optimize image size or rebuild times compared to `COPY` in this context, and can even introduce security risks if not used carefully.
  • C. Setting `WORKDIR` to `/tmp` is a common practice for temporary files but doesn't directly optimize image size or build times in the way multi-stage builds do.

Docker Multi-Stage Builds

Multi-stage builds in Dockerfiles allow you to create smaller, more secure images by using separate build stages to compile code and then copying only the essential runtime artifacts to a final, lean image.

  • Reduces final image size significantly.
  • Improves security by removing build dependencies.
  • Optimizes layer caching for faster rebuilds.
  • Uses multiple `FROM` instructions.

Memory trick: Multi-stage: build then trim, for a lean, mean image.

More Application Deployment and Security questions