Containers and images

Cloud, deploys and infrastructure Junior Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Pick the fix

Every code change makes the image build reinstall all dependencies. Fix?

Options
Hint 1 of 1

Which layer changes on every commit?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Copy the lock file and install dependencies before copying the source

Correct. The dependency layer stays cached.

Docker reuses a cached layer until one of its inputs changes. If the lock file and dependency install come before COPY of the source, code edits only rebuild the layers after them.

Why not the others?
  • B Use a bigger build machine. Still reinstalls.
  • C Remove the lock file. Makes builds unreproducible.
  • D Install dependencies at container start. Slow starts and unpinned results.

30-second answer

Small, reproducible and safe. Start from a slim, pinned base image, install locked dependencies in an early layer so code changes don't rebuild them, copy the app last, and use a multi-stage build so compilers stay out of the final image. Run as a non-root user, configure with environment variables, write logs to stdout, and keep one process per container. Scan images and rebuild regularly for security patches.

Practise saying it · 25 s. No recording, just a timer

Good images.

Say your answer out loud, then check which of these points you covered:

  • Slim pinned base
  • Dependencies before code
  • Multi-stage
  • Non-root
  • No secrets in layers

Deep dive

Pin base images by digest for reproducibility.

A .dockerignore keeps secrets and .git out of the build context.

Never bake secrets into layers; they stay in the image history.

Distroless or slim images reduce attack surface.

Common mistakes

  • Running as root.
  • COPY . . before installing dependencies, so every change reinstalls them.
  • Secrets in ENV lines in the Dockerfile.

Senior take & follow-ups

Slim pinned base, layer order, multi-stage, non-root, no secrets, scanning.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why order layers?

    Show hint

    Docker caches layers; put rarely changing ones first.

  2. Why multi-stage?

    Show hint

    Build tools stay in the builder stage.

Suggest a fix if something here is wrong or out of date.