Skip to content

Lesson 8 of 24Real apps

Dockerizing a Full-Stack App

Containerise a React frontend, a FastAPI backend, and a Next.js app with small multi-stage images and a fast dev loop.

27 min read0/6 questions

This is the lesson where everything comes together: a real monorepo with a React frontend and a FastAPI backend, shipped as small production images, with a development setup that still hot-reloads when you save a file. It is also the exact setup you can describe in a portfolio project and in interviews.

The project

shop (monorepo)
  • shop/
  • frontend/React + Vite
  • src/
  • public/
  • package.json
  • package-lock.json
  • vite.config.ts
  • nginx.confserves the built files, proxies /api
  • Dockerfile
  • .dockerignorenode_modules, dist, .env
  • backend/FastAPI, managed with uv
  • app/
  • main.py
  • tests/
  • pyproject.toml
  • uv.lock
  • Dockerfile
  • .dockerignore.venv, __pycache__, .env
  • compose.yamlproduction-like stack
  • compose.dev.yamldev overrides: bind mounts, reload
  • .env.example

Each app has its own Dockerfile and its own .dockerignore, and its folder is its build context. The root holds the Compose files that wire them together.

Multi-stage builds

Building a React app needs Node, npm, and hundreds of megabytes of node_modules. Running it needs none of that: npm run build outputs plain HTML, CSS, and JavaScript files in dist/, which any web server can serve.

A multi-stage build uses several FROM lines in one Dockerfile. Each FROM starts a fresh stage. You do the heavy work in a builder stage, then start a clean runtime stage and copy only the finished output across with COPY --from=<stage>. Only the last stage becomes your image.

What ends up in the final image
  1. runtime: nginx:1.27-alpineabout 50 MB
  2. COPY --from=build /app/distabout 1 MB of static files
  3. build: node:22-alpineabout 160 MB
  4. npm ci (node_modules)about 300 MB
  5. COPY . . + npm run buildsource + dist/

Build stage: Node installs dependencies and compiles the app. This stage is big, but it is only a means to an end.

1/3

Here is the idea in plain Python. Only what is explicitly copied survives into the final stage.

Pythonmultistage.py
build_stage = { # path -> size in MB "/usr/local/bin/node": 95, "/app/node_modules": 310, "/app/src": 2, "/app/dist": 1,}runtime_base = {"/usr/sbin/nginx": 48} copies = ["/app/dist"] # COPY --from=build /app/dist ...final = dict(runtime_base)for path in copies: final["/usr/share/nginx/html"] = build_stage[path] print("build stage:", sum(build_stage.values()), "MB")print("final image:", sum(final.values()), "MB")print("node in final image?", "/usr/local/bin/node" in final)
Output
Press Run (⌘ Enter) to see what happens.
Quick check
In a two-stage Dockerfile, which stage becomes the image that docker build -t web . produces?
Need a nudge? A hint rules out a wrong answer.

The React frontend, served by Nginx

frontend/Dockerfile
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
ARG VITE_API_URL=/api
RUN npm run build
 
FROM nginx:1.27-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
 
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80

npm ci installs exactly what package-lock.json says, which is what you want in a build. The Nginx base image already has a sensible CMD that runs Nginx in the foreground, so you do not need one.

frontend/nginx.conf
server {
  listen 80;
  root /usr/share/nginx/html;
 
  location /api/ {
    proxy_pass http://api:8000/;
  }
 
  location / {
    try_files $uri /index.html;
  }
}

Two jobs here. /api/ requests are proxied to the api service by name, so the browser only ever talks to one origin and you avoid CORS. Every other path falls back to index.html, so client-side routes like /orders/42 work on refresh.

Quick check
You set VITE_API_URL with environment: in compose.yaml for the Nginx container, but the React app still uses the old URL. Why?
Need a nudge? A hint rules out a wrong answer.

The FastAPI backend, with uv

uv installs Python packages very quickly from a lockfile, and its Docker pattern mirrors what you learned about caching: dependencies first, project second.

backend/Dockerfile
FROM python:3.13-slim AS build
COPY --from=ghcr.io/astral-sh/uv:0.9 /uv /bin/uv
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN uv sync --locked --no-dev --no-install-project
COPY app/ ./app/
RUN uv sync --locked --no-dev
 
FROM python:3.13-slim
RUN useradd --create-home app
WORKDIR /app
COPY --from=build --chown=app:app /app /app
ENV PATH="/app/.venv/bin:$PATH"
USER app
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
  • COPY --from=ghcr.io/astral-sh/uv:0.9 copies a file straight out of another image. That is how you get the uv binary without installing it.
  • uv sync --locked fails if uv.lock is out of date, so the image always matches the lockfile. --no-dev skips pytest and friends.
  • The first uv sync installs only dependencies (cached until the lockfile changes); the second adds your project.
  • The runtime stage copies the finished /app/.venv and puts it on PATH. No uv, no compilers, no build cache. Both stages use the same base image so the virtualenv's Python paths match.
Put it in order6 steps

Order the backend build stage for the best caching.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Pinning uv, and where its cache goes

ghcr.io/astral-sh/uv:0.9 is a moving tag: it follows the newest 0.9.x release. That is a reasonable default, because uv releases often and patch releases are fixes. Two upgrades are worth making in a team repo:

  • Pin to a digest when you want builds that never change under you: COPY --from=ghcr.io/astral-sh/uv:0.9.5@sha256:<digest> /uv /uvx /bin/. Dependabot or Renovate can bump the tag and digest together in a reviewed PR. The version here is an example; check the uv releases page for the current one.
  • Keep uv's download cache out of the layer. The uv sync lines above download wheels into a cache inside the image's filesystem. A BuildKit cache mount keeps that cache between builds instead, so a lockfile change only downloads what is new. BuildKit, Cache Mounts and Advanced Multi-Stage Builds, later in this track, shows the exact --mount=type=cache line and why UV_LINK_MODE=copy matters with it.

The official image also ships uvx, which runs a tool once without installing it into the project. You rarely need it in a production image, but it is handy in a CI or tooling stage.

A test stage, run with --target

Your CI should test the code that ships, with the same Python, the same system libraries and the same locked dependencies. The cleanest way is to make the tests a stage of the same Dockerfile.

backend/Dockerfile
FROM python:3.13-slim AS build
COPY --from=ghcr.io/astral-sh/uv:0.9 /uv /bin/uv
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN uv sync --locked --no-dev --no-install-project
COPY app/ ./app/
RUN uv sync --locked --no-dev
 
# tests: same base, same lockfile, plus the dev group
FROM build AS test
RUN uv sync --locked
COPY tests/ ./tests/
RUN uv run pytest -q
 
FROM python:3.13-slim AS runtime
RUN useradd --create-home app
WORKDIR /app
COPY --from=build --chown=app:app /app /app
ENV PATH="/app/.venv/bin:$PATH"
USER app
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

test starts from build, so it reuses every cached layer and only adds pytest and the tests. CI then runs two builds:

docker build --target test ./backend                  # fails the job if pytest failsdocker build --target runtime -t api:sha-7f3c2a1 ./backend

The second build is almost free: build is already cached from the first.

Here is the detail that surprises people. BuildKit builds only the stages the requested target depends on. runtime copies from build, never from test, so a plain docker build -t api . skips the tests completely. That is a feature: local builds stay fast. It also means a CI pipeline that forgets --target test ships untested images while every build looks green.

Some teams force the dependency by copying a marker file from test into runtime. That guarantees the tests ran, but now every build runs them, including the one on your laptop. Two separate commands in CI is usually the better trade.

Tests that need Postgres do not belong inside docker build, because builds cannot reach your Compose network. Point a Compose service at the test stage instead, with build: { context: ./backend, target: test }, and run it next to the database. Compose for Local Development has the pattern for one-off services like this.

Quick check
CI runs only docker build -t api:sha ./backend with the Dockerfile above. A developer pushes a commit that breaks a unit test. What happens?
Need a nudge? A hint rules out a wrong answer.

Next.js: standalone output

If your frontend is Next.js rather than a static Vite build, it needs a Node server at runtime. Next can trace exactly which files the server needs and copy them into .next/standalone, including a minimal server.js. Turn it on in the config:

next.config.ts
import type { NextConfig } from "next";
 
const nextConfig: NextConfig = {
  output: "standalone",
};
 
export default nextConfig;
web/Dockerfile
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
 
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0
COPY --from=build --chown=node:node /app/.next/standalone ./
COPY --from=build --chown=node:node /app/.next/static ./.next/static
COPY --from=build --chown=node:node /app/public ./public
USER node
EXPOSE 3000
CMD ["node", "server.js"]

The standalone folder does not include public/ or .next/static/ (those are usually served by a CDN), so you copy them in yourself. HOSTNAME=0.0.0.0 is the Next.js version of uvicorn's --host 0.0.0.0.

Three Next.js gotchas in containers

HOSTNAME is a shared name. server.js binds to the address in HOSTNAME, but container runtimes commonly set HOSTNAME to the container's own hostname. If the image's ENV HOSTNAME=0.0.0.0 is missing or a platform overrides it, the server binds only to the container's network address. Traffic through the load balancer may work while a healthcheck to localhost inside the container fails, or the other way round, which makes no sense until you look. The startup log prints the address it is listening on; read it. Setting the variable in the platform's task or pod environment as well as the image removes the doubt.

sharp must match the runtime. next/image optimises images in production with the sharp library, which ships prebuilt native binaries per platform as optional npm packages (for example a linuxmusl-arm64 build for Alpine on ARM). Recent Next.js versions install and trace it for you. It breaks when the binary in the image is for a different platform than the container: installing with optional packages turned off, copying node_modules from your Mac into the build, or building the build stage for one architecture and running another. The symptom is that pages render but every optimised image returns a 500, with a log line saying sharp could not load for your platform. Install inside the Linux build stage, keep node_modules in .dockerignore, and build for the platform you run.

Monorepos nest the output. When the app lives in apps/web and file tracing starts at the repo root, the standalone folder mirrors that path, so server.js ends up at .next/standalone/apps/web/server.js, not at the top. CMD ["node", "server.js"] then fails with "Cannot find module". List the standalone folder after a build (docker build --target build and look) and copy or start from the real path. The tracing root setting is described in the Next.js output docs.

Before and after

Typical uncompressed sizes for this kind of app. Yours will vary, but the ratio will not.

ImageSingle stage, full baseMulti-stage, slim runtime
React + Vite frontendnode:22 + node_modules: about 1.4 GBnginx:1.27-alpine + dist: about 50 MB
FastAPI backendpython:3.13 + build tools: about 1.1 GBpython:3.13-slim + .venv: about 190 MB
Next.js appnode:22 + all of node_modules: about 1.6 GBnode:22-alpine + standalone: about 220 MB

Smaller images pull faster (quicker deploys and autoscaling), cost less to store, and contain fewer packages that can have vulnerabilities.

An image size budget

A one-off slimming pass decays. Six months later someone adds build-essential to the runtime stage "just to get a wheel to compile", and the image is back to 450 MB. Teams that keep images small treat size like a performance budget: a number per image, checked in CI.

Finding where the bytes went is the job of docker history and dive, which Image Layers and the Build Cache walks through later in this track. This is what that output looked like for the backend before and after a fix:

Layer (from dive)BeforeAfterWhy
FROM python:3.13-slim125 MB125 MBThe base is fixed cost; choose it once
RUN apt-get install build-essential210 MBgoneCompilers belong in the build stage only
COPY --from=build /app/.venv64 MB64 MBLocked dependencies, --no-dev
COPY app/ ./app/38 MB2 MBA 36 MB test fixture lived under app/

Run this checker, which applies a per-part budget to both layer lists.

Pythonsize_budget.py
BUDGET_MB = {"base": 130, "venv": 70, "app": 5, "other": 5} def classify(created_by: str) -> str: if created_by.startswith("FROM"): return "base" if ".venv" in created_by: return "venv" if "app/" in created_by: return "app" return "other" def check(name: str, layers: list[tuple[str, int]]) -> None: used = {k: 0 for k in BUDGET_MB} for created_by, mb in layers: used[classify(created_by)] += mb print(name, "total", sum(used.values()), "MB") for part, limit in BUDGET_MB.items(): flag = "OVER" if used[part] > limit else "ok" print(f" {part:<6} {used[part]:>4} / {limit:<4} {flag}") check("before", [ ("FROM python:3.13-slim", 125), ("RUN apt-get install build-essential", 210), ("COPY --from=build /app/.venv /app/.venv", 64), ("COPY app/ ./app/", 38),])check("after", [ ("FROM python:3.13-slim", 125), ("COPY --from=build /app/.venv /app/.venv", 64), ("COPY app/ ./app/", 2),])
Output
Press Run (⌘ Enter) to see what happens.

In CI the input is one command, docker image inspect -f '{{.Size}}' api:sha-7f3c2a1, which prints bytes, plus a small script that fails the job above the budget. The budget is not about disk. Every megabyte is pulled on every new node and every scale-out, so it shows up as slower autoscaling and slower rollbacks, exactly when you need them fast.

Dev and prod setups

The production images are great for shipping and terrible for coding: every change means a rebuild. In development you want your editor's saves to show up instantly. The usual answer is a second Compose file that overrides the first with bind mounts and reload commands.

compose.dev.yaml
services:
  api:
    build: ./backend
    command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
    volumes:
      - ./backend/app:/app/app
 
  frontend:
    image: node:22-alpine
    working_dir: /app
    command: sh -c "npm ci && npm run dev -- --host 0.0.0.0"
    ports: ["5173:5173"]
    volumes:
      - ./frontend:/app
      - /app/node_modules
docker compose -f compose.yaml -f compose.dev.yaml up --build

Later files override earlier ones key by key. The bind mount puts your live source over the code baked into the image, and --reload restarts uvicorn on save. For the frontend, the Vite dev server replaces Nginx entirely.

That last line, - /app/node_modules, is an anonymous volume. It sits on top of the bind mount at that one path, so the container keeps its own Linux node_modules instead of seeing the ones on your Mac, which may contain native binaries built for macOS.

Quick check
You remove the - /app/node_modules line from compose.dev.yaml. On a Mac with its own node_modules folder, Vite now crashes with an error about a missing native binary for linux-arm64. Why?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/4 matched

Match each runtime stage to the app it serves.

Choose an item, then its match on the other side.
Key terms
multi-stage build
A Dockerfile with several FROM stages; only the last becomes the image, copying just the build output across.
COPY --from
Copy files from an earlier stage, or from any other image, into the current stage.
standalone output
Next.js output: "standalone": a minimal server.js plus only the files the server needs.
build-time variable
A value baked into the build output (like Vite's import.meta.env), so changing it needs a rebuild.
anonymous volume
An unnamed volume, often used to mask one path (like node_modules) under a bind mount.
--target
docker build --target build stops at a named stage, useful for debugging or dev images.
test stage
A Dockerfile stage that runs the test suite on the same base and lockfile as the image that ships.
size budget
A size limit per image, checked in CI, so slimming work does not quietly decay.