Skip to the page

Containers · Write code

Review this Dockerfile

The interviewer asks

A team wants to ship this Dockerfile for a Python API. Every build takes eight minutes even for a one-line change, and the image is 1.4 GB. What would you change, and why?

FROM python:latest
ENV DATABASE_URL=postgres://app:S3cret@prod-db:5432/orders
WORKDIR /app
COPY . .
RUN apt-get update
RUN apt-get install -y gcc libpq-dev curl vim
RUN pip install -r requirements.txt
EXPOSE 8000
CMD python -m uvicorn main:app --host 0.0.0.0 --port 8000

Then

Follow-ups the interviewer asks next

  1. Why does a one-line code change reinstall every package?
  2. Why is the password a problem even if a later line removes it?
  3. What's wrong with the shell form of CMD here?
  4. How do you get gcc to build wheels without shipping it?
  5. What goes in .dockerignore?
  6. Rewrite it.

The answer

What a strong answer covers

  • latest floats, so builds aren't repeatable and a new Python version can arrive silently. Pin a version and a slim variant (python:3.13-slim), ideally by digest.
  • A secret in ENV is baked into the image config and history; anyone who can pull the image can read it (docker history, docker inspect). Pass it at runtime from a secret store; for build-time secrets use BuildKit RUN --mount=type=secret. Rotate this password now.
  • Cache: COPY . . before installing dependencies means any file change invalidates the pip layer. Copy requirements.txt first, install, then copy the code; add a cache mount (RUN --mount=type=cache,target=/root/.cache/pip).
  • apt-get update alone in a layer gets cached and goes stale: combine apt-get update && apt-get install -y --no-install-recommends … && rm -rf /var/lib/apt/lists/* in one RUN. No vim or curl in production images.
  • Multi-stage: a builder stage with gcc and libpq-dev builds wheels; the final stage installs those wheels with only the runtime library (libpq5).
  • It runs as root: add a user and USER app.
  • Shell-form CMD runs under /bin/sh -c, so sh is PID 1 and SIGTERM may never reach uvicorn. Use the exec form: CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"].
  • .dockerignore: .git, .venv, __pycache__, test data, .env (otherwise COPY . . ships local secrets too).

The red pen

Common traps

Avoid:"add --no-cache to make it faster"; "unset the variable in a later line"; moving to Alpine without checking that the Python wheels exist for musl.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview