Recipe
Put a Rust service in a small image
Use when: a Rust program has to be delivered as a container image
Goal: a multi-stage Dockerfile whose shipped stage holds only the executable, its data, and the libraries it links
Taught in Containers
Quick recipe
-
1
Read its port and file locations from environment variables, listen on
0.0.0.0, and shut down cleanly on SIGTERM.Why: inside a container, 127.0.0.1 is unreachable from outside and PID 1 ignores a signal it doesn't handle.
-
2
FROMa Rust imageAS build, copyCargo.toml,Cargo.lockandsrc/, and runcargo build --release --locked.Why: the toolchain stays in a stage that is never shipped, and
--lockedbuilds exactly the reviewed versions. -
3
scratchor distroless static for musl, distroless cc for glibc, a slim distribution only if you need its tools.Example
dockdis a glibc build fromrust:1.98-slim-trixie, so its runtime base isgcr.io/distroless/cc-debian13:nonroot: the same Debian release, a non-root user.Why: the image must provide exactly what
lddwould list, and nothing it doesn't need. -
4
COPY --from=buildthe executable and its data files, setENVandEXPOSE, and make it theENTRYPOINT.Why: whatever isn't copied isn't downloaded, stored or attackable.
-
5
Add a
.dockerignorefortarget/, and a cargo-chef stage so dependencies rebuild only when the manifest or lock changes.Why: without it, every source edit recompiles every crate.