A multi-stage build is one Dockerfile with several FROM instructions. Each FROM starts a new stage. A later stage can copy chosen files from an earlier stage with COPY --from=<stage>. Only the last stage becomes the image. You can pick a different stage with --target.
For a TypeScript service, the build works like this:
- The build stage installs all dependencies, including the TypeScript compiler and the Nest CLI.
- The build stage runs
npm run build. - The final stage starts from a clean base image.
- The final stage copies only the compiled
distfolder and the productionnode_modules.
The result is a smaller image with a smaller attack surface (the parts an attacker could use). The final image has:
- no compiler
- no dev dependencies
- no source maps or test files, unless you want them
- no build tools
It also keeps the build steps and the runtime setup in one file, instead of separate build scripts.
- A multi-stage build has several FROM stages in one Dockerfile.
- COPY --from copies built files from one stage to another.
- Only the final stage becomes the shipped image.
- Build tools and dev dependencies stay out of the runtime image.
- The image is smaller and has a smaller attack surface.
Read more