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.
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/
- 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.
Build stage: Node installs dependencies and compiles the app. This stage is big, but it is only a means to an end.
Here is the idea in plain Python. Only what is explicitly copied survives into the final stage.
Press Run (⌘ Enter) to see what happens.docker build -t web . produces?The React frontend, served by Nginx
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 80npm 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.
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.
VITE_API_URL with environment: in compose.yaml for the Nginx container, but the React app still uses the old URL. Why?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.
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.9copies a file straight out of another image. That is how you get theuvbinary without installing it.uv sync --lockedfails ifuv.lockis out of date, so the image always matches the lockfile.--no-devskips pytest and friends.- The first
uv syncinstalls only dependencies (cached until the lockfile changes); the second adds your project. - The runtime stage copies the finished
/app/.venvand puts it onPATH. Nouv, no compilers, no build cache. Both stages use the same base image so the virtualenv's Python paths match.
Order the backend build stage for the best caching.
- Tap the steps below in the right order.
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 synclines 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=cacheline and whyUV_LINK_MODE=copymatters 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.
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 ./backendThe 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.
docker build -t api:sha ./backend with the Dockerfile above. A developer pushes a commit that breaks a unit test. What happens?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:
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
};
export default nextConfig;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.
| Image | Single stage, full base | Multi-stage, slim runtime |
|---|---|---|
| React + Vite frontend | node:22 + node_modules: about 1.4 GB | nginx:1.27-alpine + dist: about 50 MB |
| FastAPI backend | python:3.13 + build tools: about 1.1 GB | python:3.13-slim + .venv: about 190 MB |
| Next.js app | node:22 + all of node_modules: about 1.6 GB | node: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) | Before | After | Why |
|---|---|---|---|
FROM python:3.13-slim | 125 MB | 125 MB | The base is fixed cost; choose it once |
RUN apt-get install build-essential | 210 MB | gone | Compilers belong in the build stage only |
COPY --from=build /app/.venv | 64 MB | 64 MB | Locked dependencies, --no-dev |
COPY app/ ./app/ | 38 MB | 2 MB | A 36 MB test fixture lived under app/ |
Run this checker, which applies a per-part budget to both layer lists.
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.
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_modulesdocker compose -f compose.yaml -f compose.dev.yaml up --buildLater 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.
- /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?Match each runtime stage to the app it serves.
- multi-stage build
- A Dockerfile with several
FROMstages; 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 minimalserver.jsplus 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 buildstops 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.