Day 6: Multi-Stage for Python and Node
Goal: Build notes-worker with uv and notes-web with npm in two stages so that the runtime image contains only the interpreter, prod dependencies and the app. · Duration: approx. 75 min · Prerequisite: Day 5
Briefing
- Python and Node need their interpreter at runtime, so
scratchis out. The pattern stays: tools in thebuildstage, only the result in the runtime image. - Python: uv builds a
.venv; only that is copied. uv itself, its cache and the source code stay behind. - Node: esbuild bundles into
dist/in thebuildstage; the runtime image getsdist/,server.jsand only the prodnode_modules. - Build and runtime stage must match: same base image, same interpreter path.
notes-worker notes-web
build: python:3.13-slim + uv build: node:24-alpine
uv sync --no-install-project (deps) npm ci (all deps)
uv sync --no-editable (project) npm run build → dist/app.js
│ COPY --from=build /app/.venv │ COPY --from=build /app/dist
▼ ▼
python:3.13-slim .venv, USER 65532 node:24-alpine npm ci --omit=dev,
server.js, public/, dist/, USER node
Drill 1: The naive Python build
source ~/docker-lab/setup/env.sh
mkdir -p ~/docker-lab/tag06 && cd ~/docker-lab/tag06
cp -R "$LAB/code/notes/." . && cp -R "$LAB/code/tag05/notes/." .The second copy lays the state from the end of Day 5 on top – even if you skipped it. For comparison, you first build the worker the way you often see it: one stage, everything in. The Dockerfile comes via a heredoc on stdin:
docker build -q -t notes-worker:naiv -f- notes-worker <<'EOF'
# syntax=docker/dockerfile:1
FROM python:3.13-slim
COPY --from=ghcr.io/astral-sh/uv:0.13.6 /uv /uvx /bin/
WORKDIR /app
COPY . .
RUN uv sync --locked
CMD ["uv", "run", "notes-worker"]
EOF
docker run --rm notes-worker:naiv \
sh -c 'du -sh /bin/uv /root/.cache/uv /app/.venv; ls /app'Expected (abbreviated, may vary by version):
sha256:5e81…
43.6M /bin/uv
11.2M /root/.cache/uv
4.6M /app/.venv
pyproject.toml
src
uv.lock
COPY --from=ghcr.io/astral-sh/uv:0.13.6 fetches the uv
binary directly from the official uv image, without
pip install uv; Day 7 goes deeper into this pattern. The
runtime image thus contains uv, its download cache and the source code –
the worker needs none of that. Sizes in this chapter come from a sample
environment and will differ on your machine.
Save your progress? Sign up for free
Drill 2: .dockerignore for the worker
A local .venv is tied to your operating system and must
never get into the context. The uv docs explicitly call this a best
practice.
cat > notes-worker/.dockerignore <<'EOF'
# notes-worker/.dockerignore (Day 6)
Dockerfile*
.dockerignore
.git
.env*
.venv
**/__pycache__
**/*.pyc
EOFA local uv sync creates a .venv as bait
(without uv on the Mac, leave out the first line). A throwaway build
then lists what really arrives in the context:
(cd notes-worker && uv sync -q)
docker build --no-cache --progress=plain -f- notes-worker <<'EOF' 2>&1 \
| grep -E '^#[0-9]+ [0-9.]+ /ctx'
# syntax=docker/dockerfile:1
FROM python:3.13-slim
COPY . /ctx
RUN find /ctx -maxdepth 1
EOFExpected (abbreviated, may vary by version):
#7 0.162 /ctx
#7 0.162 /ctx/pyproject.toml
#7 0.162 /ctx/src
#7 0.162 /ctx/uv.lock
No .venv, no .dockerignore (the order may
vary). The build doesn’t create a named image, only cache.
Save your progress? Sign up for free
Drill 3: uv in two stages
The pattern follows the official uv Docker docs
(docs.astral.sh/uv/guides/integration/docker/):
cat > notes-worker/Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
# notes-worker, state Day 6: uv in the build stage, only the .venv in the runtime image
ARG PYTHON_VERSION=3.13
# in production: pin @sha256:…, see Day 8
FROM python:${PYTHON_VERSION}-slim AS build
COPY --from=ghcr.io/astral-sh/uv:0.13.6 /uv /uvx /bin/
ENV UV_COMPILE_BYTECODE=1 \
UV_LINK_MODE=copy \
UV_NO_DEV=1 \
UV_PYTHON_DOWNLOADS=0
WORKDIR /app
RUN --mount=type=cache,target=/root/.cache/uv \
--mount=type=bind,source=uv.lock,target=uv.lock \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
uv sync --locked --no-install-project --no-editable
COPY . .
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --locked --no-editable --reinstall-package notes-worker
FROM python:${PYTHON_VERSION}-slim
LABEL org.opencontainers.image.title="notes-worker" \
org.opencontainers.image.description="Fasst die Notizen aus notes-api zusammen" \
org.opencontainers.image.source="https://example.com/docker-lab/notes"
COPY --from=build /app/.venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH"
WORKDIR /app
USER 65532:65532
STOPSIGNAL SIGTERM
ENTRYPOINT ["notes-worker"]
EOF| Setting | Effect |
|---|---|
UV_COMPILE_BYTECODE=1 |
.pyc already at build time; as user 65532, Python can’t
write them later |
UV_LINK_MODE=copy |
cache mount and .venv are on different file systems:
copy instead of link |
UV_NO_DEV=1 |
no dev dependencies |
UV_PYTHON_DOWNLOADS=0 |
use the base image’s Python, don’t download one |
--locked |
abort if uv.lock doesn’t match
pyproject.toml |
--no-install-project |
only the dependencies first – a separate, stable layer |
--no-editable |
project as a package in the .venv, not as a reference
to src/ |
--reinstall-package notes-worker |
always rebuild your own project (Drill 4) |
UV_PYTHON_DOWNLOADS=0 is the key to the second stage:
the .venv points to /usr/local/bin/python3
from python:3.13-slim, and exactly this path exists again
in the runtime image, because both stages use the same
ARG PYTHON_VERSION. In the first uv sync,
uv.lock and pyproject.toml are only present
via bind mount; so the layer doesn’t depend on the source code.
docker build -t notes-worker:tag06 notes-workerExpected (abbreviated, may vary by version):
[+] Building 14.2s (15/15) FINISHED docker:colima
=> [internal] load metadata for ghcr.io/astral-sh/uv:0.13.6 1.1s
=> [internal] load metadata for docker.io/library/python:3.13-slim 0.9s
=> [build 1/6] FROM docker.io/library/python:3.13-slim@sha256:… 4.8s
=> FROM ghcr.io/astral-sh/uv:0.13.6@sha256:… 2.3s
=> [build 2/6] COPY --from=ghcr.io/astral-sh/uv:0.13.6 /uv /uvx /bin/ 0.2s
=> [build 3/6] WORKDIR /app 0.0s
=> [build 4/6] RUN --mount=type=cache,target=/root/.cache/uv --mount… 2.9s
=> [build 5/6] COPY . . 0.0s
=> [build 6/6] RUN --mount=type=cache,target=/root/.cache/uv uv sync… 2.4s
=> [stage-1 2/3] COPY --from=build /app/.venv /app/.venv 0.1s
=> [stage-1 3/3] WORKDIR /app 0.0s
=> exporting to image 0.4s
In the last uv sync, uv builds a wheel of notes-worker.
For that it loads the build backend from [build-system]
(hatchling) into an isolated environment; that isn’t in
uv.lock. Hatchling finds the package in the
src/ layout by itself: the project name
notes-worker matches src/notes_worker/.
Save your progress? Sign up for free
Drill 4: What’s in the image – and what isn’t
docker run --rm --entrypoint sh notes-worker:tag06 -c '
command -v uv || echo "kein uv"
ls -A /app
id -u
ls /app/.venv/lib/python3.13/site-packages | grep notes
find /app/.venv -name "*.pyc" | wc -l'
docker image ls notes-worker --format '{{.Tag}}\t{{.Size}}'Expected (abbreviated, may vary by version):
kein uv
.venv
65532
notes_worker
notes_worker-0.1.0.dist-info
128
tag06 127MB
naiv 186MB
No uv, no src/, no uv.lock; the package
sits in site-packages as a real package. With an editable
install there would only be a .pth file pointing to
/app/src – and that doesn’t exist in the runtime image. The
biggest chunk is the roughly 120 MB of python:3.13-slim
itself; Day 8 compares smaller base images.
Now the cache. Change the code and build once
without --reinstall-package (via
sed on stdin) and once with the real file:
echo '# Tag 6' >> notes-worker/src/notes_worker/__init__.py
sed 's/ --reinstall-package notes-worker//' notes-worker/Dockerfile \
| docker build -q -f- -t notes-worker:stale notes-worker
docker build --progress=plain -t notes-worker:tag06 notes-worker 2>&1 \
| grep -E '^#[0-9]+ (\[build [456]/6\]|CACHED)|Built|Installed'
init=/app/.venv/lib/python3.13/site-packages/notes_worker/__init__.py
for t in stale tag06; do
docker run --rm --entrypoint tail notes-worker:$t -n 1 "$init"
done
docker rmi -f notes-worker:stale >/dev/nullExpected (abbreviated, may vary by version):
sha256:2a7f…
#6 CACHED
#7 CACHED
#8 [build 4/6] RUN --mount=type=cache,target=/root/.cache/uv --mount=type=bind,s…
#8 CACHED
#10 [build 5/6] COPY . .
#11 [build 6/6] RUN --mount=type=cache,target=/root/.cache/uv uv sync --locked …
#11 0.981 Built notes-worker @ file:///app
#11 1.204 Installed 1 package in 2ms
print("worker stopped", flush=True)
# Tag 6
In both cases the dependency layer comes from the cache; only
notes-worker is reinstalled. But notes-worker:stale
contains the old code: according to the docs, uv only
rebuilds local projects when pyproject.toml,
setup.py or setup.cfg change or a
src folder is added or removed. The cache mount still held
the wheel from Drill 3. --reinstall-package notes-worker
forces the rebuild; the alternative is [tool.uv] cache-keys
in pyproject.toml.
Save your progress? Sign up for free
Drill 5: Worker against notes-api
The worker talks to http://notes-api:8080. A dedicated
network provides name resolution via the container name.
docker build -q -t notes-api:tag06 notes-api
docker network create notes-net
docker run -d --name notes-api --network notes-net -p 127.0.0.1:8080:8080 \
-e NOTES_API_KEY=lab-api-key-123 notes-api:tag06
docker run -d --name notes-worker --network notes-net -e INTERVAL=3 \
-e NOTES_API_KEY=lab-api-key-123 notes-worker:tag06
curl -s -X POST localhost:8080/notes -H 'X-API-Key: lab-api-key-123' \
-d '{"text":"uv in zwei Stages"}'
sleep 4; docker logs notes-workerExpected (abbreviated, IDs differ):
sha256:8c1e…
7f3a2c…
4d9b0e…
1b6f8a…
{"id":"c0d2…","text":"uv in zwei Stages"}
worker started, api=http://notes-api:8080, interval=3s
summary: 1 notes, 4 words
The three hex lines are the IDs of the network and the containers.
Stopping is instant, because notes-worker runs as PID 1 via
exec form and handles SIGTERM itself:
time docker stop notes-worker
docker logs --tail 2 notes-workerExpected (abbreviated, times differ):
notes-worker
docker stop notes-worker 0.01s user 0.01s system 4% cpu 0.341 total
signal 15 received, stopping
worker stopped
The container and network stay up for Drill 7.
Save your progress? Sign up for free
Drill 6: notes-web with npm in two stages
cat > notes-web/.dockerignore <<'EOF'
# notes-web/.dockerignore (Day 6)
Dockerfile*
.dockerignore
.git
.env*
.npmrc
node_modules
dist
EOF
cat > notes-web/Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
# notes-web, state Day 6: bundle in the build stage, only prod dependencies at runtime
ARG NODE_VERSION=24
# in production: pin @sha256:…, see Day 8
FROM node:${NODE_VERSION}-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build
FROM node:${NODE_VERSION}-alpine
LABEL org.opencontainers.image.title="notes-web" \
org.opencontainers.image.description="Oberfläche und Proxy für notes-api" \
org.opencontainers.image.source="https://example.com/docker-lab/notes"
ENV NODE_ENV=production
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev
COPY server.js ./
COPY public ./public
COPY --from=build /app/dist ./dist
EXPOSE 3000
USER node
STOPSIGNAL SIGTERM
ENTRYPOINT ["node", "server.js"]
EOF
docker build -q -t notes-web:tag06 notes-webExpected (abbreviated, may vary by version):
sha256:e27c…
Three decisions are in there:
- Two
npm ci. Thebuildstage needs esbuild (a devDependency), the runtime image doesn’t.npm ci --omit=devinstalls exactly according topackage-lock.json, just without dev packages..npmrcis already in the.dockerignore; on Day 13 it comes back as a build secret. package.jsonbelongs in the runtime image. notes-web is an ES module ("type": "module"). Node 24 recognizesimporteven without this field via syntax detection, but then parses the file twice; with apackage.jsonwithouttypeit additionally warns withMODULE_TYPELESS_PACKAGE_JSON. Only thetypefield is unambiguous.USER node. The official Node images come with the usernode(UID 1000). The files belong to root and are read-only fornode– exactly right.
Save your progress? Sign up for free
Drill 7: The whole chain
docker start notes-worker
docker run -d --name notes-web --network notes-net -p 127.0.0.1:3000:3000 \
-e NOTES_API_KEY=lab-api-key-123 notes-web:tag06
sleep 2
curl -s localhost:3000/healthz; echo
curl -s -X POST localhost:3000/api/notes -H 'Content-Type: application/json' \
-d '{"text":"über notes-web"}'; echo
curl -s localhost:3000/api/notes; echo
sleep 3; docker logs --tail 1 notes-workerExpected (abbreviated, IDs differ):
notes-worker
5a07e1…
ok
{"id":"e91f…","text":"über notes-web"}
[{"id":"c0d2…","text":"uv in zwei Stages"},{"id":"e91f…","text":"über notes-web"}]
summary: 2 notes, 6 words
The browser doesn’t send a key; notes-web adds it on the server side.
Open http://localhost:3000 and create a note through the
UI. What’s in the image?
docker run --rm --entrypoint sh notes-web:tag06 -c '
ls node_modules | wc -l
ls -d node_modules/esbuild src 2>&1
ls dist
id -un'Expected (abbreviated, may vary by version):
65
ls: node_modules/esbuild: No such file or directory
ls: src: No such file or directory
app.js
node
No esbuild, no src/, only the bundle. In the
build stage there were 67 entries under
node_modules; the difference is esbuild and
its platform binary under @esbuild/.
Save your progress? Sign up for free
Drill 8: Comparison and clean shutdown
docker image ls --format '{{.Repository}}:{{.Tag}}\t{{.Size}}' \
| grep -E '^notes-(api|worker|web):' | sort
docker stop notes-web notes-worker notes-api
docker logs --tail 1 notes-web
docker logs --tail 1 notes-api
docker rm notes-web notes-worker notes-api
docker network rm notes-netExpected (abbreviated, may vary by version):
notes-api:tag06 6.31MB
notes-web:tag06 168MB
notes-worker:naiv 186MB
notes-worker:tag06 127MB
notes-web
notes-worker
notes-api
SIGTERM received, shutting down
time=… level=INFO msg="shutdown complete"
notes-web
notes-worker
notes-api
notes-net
The end-of-day cleanup removes containers and images, but not
networks – hence the docker network rm at the end. All
three services shut down cleanly on SIGTERM.
Tip: There are also distroless images for Python and Node (
gcr.io/distroless/python3-debian13,gcr.io/distroless/nodejs24-debian13). For Python, the interpreter there is at/usr/bin/python, not at/usr/local/bin/pythonas in the build image; the.venvthen points to nothing unless you align the paths. You try it for Node in the challenge.
Save your progress? Sign up for free
Checkpoint
The worker’s dependencies have their own layer:
cd ~/docker-lab/tag06
grep -c -- '--no-install-project' notes-worker/DockerfileExpected:
1
.venv stays outside the context:
grep -x '.venv' notes-worker/.dockerignoreExpected:
.venv
No uv in the worker image (127 means “command not found”):
docker run --rm --entrypoint sh notes-worker:tag06 -c 'command -v uv; echo "Exit: $?"'Expected:
Exit: 127
Neither image runs as root:
docker image inspect --format '{{.Config.User}}' notes-worker:tag06 notes-web:tag06Expected:
65532:65532
node
No esbuild in the web image:
docker run --rm --entrypoint ls notes-web:tag06 node_modules | grep -c esbuildExpected:
0
The day’s network is gone again:
docker network ls -q --filter name=notes-net | wc -lExpected:
0
Challenge
Additionally build notes-web as
notes-web:tag06-distroless on
gcr.io/distroless/nodejs24-debian13:nonroot, with the same
functionality as notes-web:tag06. Compare the size and show
that neither a shell nor npm is in the image.
Hint: distroless has no npm, so you
need a third stage for the prod dependencies; the image’s entrypoint is
already node.
Solution
The file is also available at
~/docker-lab/code/tag06/Dockerfile.web-distroless.
# syntax=docker/dockerfile:1
# Solution Challenge Day 6: notes-web on distroless/nodejs (no shell, no npm)
ARG NODE_VERSION=24
# in production: pin @sha256:…, see Day 8
FROM node:${NODE_VERSION}-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build
FROM node:${NODE_VERSION}-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev
# The image's entrypoint is already "node"; CMD only names the script
FROM gcr.io/distroless/nodejs24-debian13:nonroot
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY package.json server.js ./
COPY public ./public
COPY --from=build /app/dist ./dist
EXPOSE 3000
USER 65532:65532
CMD ["server.js"]build and deps don’t depend on each other;
BuildKit builds them in parallel (Day 7). node_modules from
an Alpine stage only works here because Express is pure JavaScript.
Packages with native addons must be built in a glibc stage such as
node:24-slim, matching the Debian base of distroless.
cd ~/docker-lab/tag06
docker build -q -f ~/docker-lab/code/tag06/Dockerfile.web-distroless \
-t notes-web:tag06-distroless notes-web
docker run -d --name notes-web -p 127.0.0.1:3000:3000 notes-web:tag06-distroless
sleep 2; curl -s localhost:3000/healthz; echo
docker run --rm --entrypoint sh notes-web:tag06-distroless -c true 2>/dev/null
echo "Exit: $?"
docker run --rm --entrypoint npm notes-web:tag06-distroless --version 2>/dev/null
echo "Exit: $?"
docker image ls notes-web --format '{{.Tag}}\t{{.Size}}'Expected (abbreviated, may vary by version):
sha256:91d4…
3c5e…
ok
Exit: 127
Exit: 127
tag06-distroless 171MB
tag06 168MB
It hardly gets smaller: distroless/nodejs is based on Debian with
glibc, node:24-alpine on musl. The gain is the attack
surface – no shell, no npm, no package manager. Without a
NOTES_API_URL target only the proxy fails here;
/healthz still responds. Finally, clean up:
docker ps -a --filter name=^notes- --format '{{.Names}}' | xargs -r docker rm -f
docker image ls --format '{{.Repository}}:{{.Tag}}' \
| grep -E '^(notes-|localhost:5001/)' | xargs -r docker rmi
docker buildx prune --builder docker-lab --all --forceExpected (abbreviated, names, IDs and sizes differ):
notes-web
Untagged: notes-web:tag06
Deleted: sha256:…
…
Total: …
Save your progress? Sign up for free
Enterprise Note
- In companies, packages come from an internal PyPI or npm proxy (Artifactory, Nexus). Its credentials never belong in the Dockerfile, but in build secrets (Day 13).
uv sync --lockedandnpm ciare mandatory in CI: a build that silently updates the lockfile isn’t reproducible and undermines dependency review.- The build backend (hatchling) and the uv image aren’t in any
lockfile. Pin both (
requires = ["hatchling==…"], uv image by digest, Day 8) or mirror them internally. - Native dependencies (e.g.
cryptography,sharp) need matching wheels or compilers: never mix musl and glibc stages; choose the same build and runtime base. - Cache mounts for uv and npm only work in CI if the builder keeps its
cache or shares it via
--cache-to/--cache-from(Day 4).