StudyToCert

All certifications / AI-200 / Lessons

Microsoft Certified: Azure AI Cloud Developer Associate AI-200 (replaced AZ-204) · Domain 1: Develop containerized solutions on Azure

Dockerfiles for Python apps: base images, multi-stage builds, non-root users, .dockerignore

▶ Watch the overview video

Last reviewed October 6, 2026 · Leer en español

Explain it simpler

A container image is a sealed lunchbox for your app: it holds your code plus everything the code needs to run, so it behaves the same on any machine. A Dockerfile is the written recipe for packing that lunchbox. Good recipes follow a few habits. Start from a small, plain base, like choosing a light container instead of a heavy one. Do your messy preparation in a separate kitchen, then pack only the finished food, which is what a multi-stage build does. Do not let the app run with full owner powers inside the box, so a burglar who gets in cannot do much. And keep a list of things that never go in the box, such as private notes and passwords. That list is the .dockerignore file.

It is Monday morning at Lakeside Freight, and Jonah from the security team drops a scan report into your team channel. The new route-planning API image is 1.2 GB, it runs as root, and the scanner found a file called .env inside one of its layers, complete with a database password. Every commit also triggers a twelve-minute rebuild because every Python package reinstalls from scratch. Nobody wrote anything malicious. The Dockerfile simply grew one line at a time, and nobody stepped back to ask what actually ends up in the final image or who the process runs as. Your lead asks you to fix it before the image goes to Azure Container Apps on Friday. Where do you start, and which four changes give you the biggest win?

A Dockerfile is the recipe that turns your Python source code into a container image: a read-only, layered package holding an operating system userland, the Python runtime, your dependencies and your code. Every Azure container service in this exam runs images built this way, including Azure App Service, Azure Container Apps, Container Apps jobs and AKS (Azure Kubernetes Service). Because all of them start from the same image, a clean Dockerfile is the first skill the rest of the domain builds on, and mistakes made here follow the image into every environment.

Start with the base image in the FROM line, because it decides most of the image size and most of the vulnerabilities a scanner will report. Official Python images come in several variants. The full Debian-based image is large but includes compilers and build tools. The -slim images drop most of those tools and are the usual choice for production. Alpine images are tiny, but they use musl instead of glibc as the C library, so many prebuilt Python wheels do not fit and packages must be compiled from source; in practice that often makes builds slower and the final image bigger than expected. Whatever you choose, pin a specific version tag, for example a Python minor version plus -slim such as python:3.12-slim, rather than latest. A pinned tag means a rebuild next month produces the same runtime you tested, not whatever happened to be newest.

Next, think about layers and caching, because they decide how fast you rebuild. Each instruction such as RUN, COPY or ADD creates a layer, and Docker caches each layer. When an instruction and its inputs are unchanged, Docker reuses the cached layer; once one layer changes, every layer after it rebuilds. So order instructions from least to most frequently changing. Copy requirements.txt first, run pip install --no-cache-dir -r requirements.txt, and only then copy the rest of your code. A code-only change then reuses the cached dependency layer instead of reinstalling every package. In a build log you can see the difference: cached steps are marked as cached and finish instantly, while a badly ordered file reinstalls everything on each commit. The --no-cache-dir flag also keeps pip's download cache out of the layer.

A multi-stage build is the main tool for keeping the final image small and clean. It uses more than one FROM. The first stage, often named builder, has compilers and headers and installs your dependencies into a virtual environment. The final stage starts again from a small runtime image and uses COPY --from=builder to bring over only the finished virtual environment and your code. Anything that lived only in the builder stage, such as build tools, caches, temporary files or credentials used to download private packages, never reaches the final image. That shrinks both the size and the attack surface, meaning the number of tools an attacker could use if they broke in. The example below shows the pattern.

FROM python:3.12-slim AS builder
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH=/opt/venv/bin:$PATH
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

FROM python:3.12-slim
RUN useradd --create-home appuser
COPY --from=builder /opt/venv /opt/venv
ENV PATH=/opt/venv/bin:$PATH
WORKDIR /app
COPY . .
USER appuser
EXPOSE 8000
CMD ["gunicorn", "-b", "0.0.0.0:8000", "app:app"]

Look at who the process runs as, because by default a container process runs as root. If an attacker exploits a flaw in your app, root inside the container makes tampering with files, installing tools and attempting a container escape much easier. The fix is two lines: create an unprivileged user (here with useradd) and switch to it with USER before CMD, as in the example. Every later instruction and the running app then use that account. A related detail is the port. Non-root users cannot bind ports below 1024 without extra Linux capabilities, so the app listens on a high port such as 8000. You then tell the hosting service which port to use, for example the target port in Container Apps or the WEBSITES_PORT setting in App Service. EXPOSE documents the port but does not publish it by itself.

Finally, control what gets sent to the build at all with .dockerignore. It works like .gitignore but for the build context, which is the set of files sent to the builder when you run a build. Files listed in .dockerignore are never sent. Typical entries are .git, __pycache__, local virtual environments such as .venv, test data, and especially .env files and local credential files. There are two reasons. First, speed: a smaller context uploads and builds faster, which matters most for remote builds that upload the context, such as az acr build. Second, secrecy: a broad COPY . . copies everything in the context into a layer, and anyone who can pull the image can extract that layer and read the file, even if a later instruction deletes it.

Put together, these four habits answer most Dockerfile questions on the exam. A slim, pinned base image keeps builds predictable. Correct instruction order keeps rebuilds fast. A multi-stage build keeps compilers and build-time secrets out of the final image. A non-root USER limits damage if the app is compromised, and .dockerignore stops sensitive or bulky files from ever reaching the builder. When a question describes a symptom, map it to the habit: slow rebuilds point to layer order, a large image with build tools points to multi-stage builds, a leaked file points to .dockerignore, and a security finding about root points to USER.

Think of it like this Think of a multi-stage build like a restaurant kitchen and the plate that goes to the table. The kitchen is full of knives, flour, scraps and the supplier's invoice. The diner receives only the finished dish. The builder stage is the kitchen; COPY --from=builder carries just the dish to the plate. The analogy stops at .dockerignore: that is not about the kitchen at all, it decides which ingredients are allowed through the back door in the first place.

Key terms

Base image
The image named in FROM that your image builds on, such as a pinned slim Python image.
Multi-stage build
A Dockerfile with several FROM stages where the final stage copies only needed artifacts from earlier stages.
Build context
The set of files sent to the builder with a build; .dockerignore removes files from it.
Layer cache
Docker's reuse of unchanged instruction results, which makes instruction order matter for build speed.
USER instruction
Sets the user that later instructions and the running container use, so the app need not run as root.
.dockerignore
A file listing paths that are excluded from the build context and therefore can never be copied into the image.
Real-world example

A team's FastAPI image was 1.1 GB and rebuilt all dependencies on every commit. They switched to a slim base, copied requirements.txt before the code, added a builder stage for compiled wheels and a .dockerignore excluding .git and .env. The final image dropped to a few hundred megabytes, rebuilds after code-only changes took seconds, and a security scan no longer flagged a leaked .env file.

Common mistakes

You decide

Your Dockerfile copies the whole project with COPY . . and then runs pip install. Every commit, even a one-line code change, reinstalls all packages and takes ten minutes. Builds run in the cloud with az acr build, and the repository includes a large .git folder. What two changes speed this up most?

Show the answer

Copy requirements.txt and run pip install before copying the rest of the code, so the dependency layer stays cached on code-only changes. Add a .dockerignore that excludes .git, virtual environments and test data, so az acr build uploads a much smaller context.

Exam tip: If a question asks how to keep compilers or secrets out of the final image, the answer is a multi-stage build; if it asks how to stop files from being sent to the build at all, the answer is .dockerignore.

Check yourself

Why should you copy requirements.txt and run pip install before copying the rest of the source code?

Because layers are cached in order; code changes then reuse the cached dependency layer instead of reinstalling every package.

What does a multi-stage build improve, and how?

Image size and security: build tools live only in an earlier stage, and the final stage uses COPY --from to take just the built artifacts.

Why run the app with a USER other than root?

To limit what an attacker can do if the app is compromised; root in the container makes tampering and escape attempts easier.

Which file keeps a local .env file from ever being sent to the builder?

.dockerignore, because it removes listed files from the build context before any COPY instruction can see them.

Study AI-200 for free
A week-by-week plan with every lesson, quizzes, checkpoint tests, a practice exam and hands-on labs.
Open the AI-200 study plan