October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Part 1.5: Optimize Dockerfiles with Multi-Stage Builds

A practical guide to separating Docker build tools from runtime contents while improving cache reuse and checking that the final image still works.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use multi-stage builds to keep compilers and other build-only tools out of your application’s runtime image: build in one named stage, then copy only the files the application needs into a final runtime stage. To improve build speed, arrange instructions so stable dependency inputs are processed before frequently changing source, and use BuildKit caches where they fit your workflow. Measure both the resulting image and rebuild behavior; a smaller image is useful only if it still contains everything the application needs to run.

How multi-stage builds work

Each FROM instruction starts a new build stage. Give a stage a name with AS, then use COPY --from=<stage> to transfer selected files into a later stage. The last stage is the default build output; you can build a named earlier stage directly with --target. See Docker’s multi-stage build documentation.

This lets you use a full build environment without shipping that environment as part of the runtime image. It does not mean the final stage can omit dependencies the application uses at runtime. Shared libraries, certificates, static assets, configuration, and other required files still need to be present.

Turn a single-stage Dockerfile into a multi-stage build

A single-stage build can install build tools, compile the application, and leave those tools in the resulting image. A multi-stage version separates those tasks and copies the build output to a runtime-compatible base.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
# Single-stage pattern: build tools remain in the resulting image
FROM <build-environment>
WORKDIR /app
COPY . .
RUN <install-build-dependencies-and-build>
CMD ["<application-start-command>"]

# Multi-stage pattern
FROM <build-environment> AS build
WORKDIR /app
COPY <dependency-manifests> ./
RUN <install-build-dependencies>
COPY . .
RUN <build-application>

FROM <runtime-compatible-base> AS runtime
WORKDIR /app
COPY --from=build /app/<build-output> ./<runtime-output>
CMD ["<application-start-command>"]

The angle-bracketed values are project-specific: choose a build environment, output path, runtime base, and startup command that match your application. The example illustrates the structure, not a ready-to-run Dockerfile. A minimal runtime base is not automatically suitable: confirm that it has the operating-system libraries and other support files your application actually uses.

Build or test an intermediate stage

Because the build stage is named, you can select it without changing the default final image:

docker build --target build -t my-app-build .

Without --target, Docker builds the last stage by default. This makes it possible to use a build or test stage for a specific workflow while keeping the production output focused on runtime contents.

Improve cache reuse by ordering instructions

Docker can reuse a cached instruction result when the relevant inputs match. When an instruction’s inputs change, that layer and downstream work are rebuilt. Put stable dependency manifests and dependency installation before frequently changing application source when your project permits it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Copy dependency manifests first, rather than copying the entire source tree immediately.

  2. Install dependencies using those manifests.

  3. Copy the remaining source files.

  4. Run the build.

The example build stage above follows this pattern. If a source edit changes files copied only after dependency installation, Docker may reuse the earlier dependency layer. If a manifest changes, dependency installation and later instructions need to run again. The exact cache behavior depends on the instructions and files in your Dockerfile.

Use BuildKit caches for build-time speed

For workflows using BuildKit, cache mounts can preserve package-manager download caches between builds, and external cache storage can help CI jobs reuse build results. These techniques target the build process; they do not automatically remove files from the published runtime image. Docker explains cache behavior and these options in its build cache guide and cache optimization guide.

For example, a BuildKit cache mount is expressed on a build instruction like this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
RUN --mount=type=cache,target=<package-manager-cache-directory> <install-dependencies>

Use the cache directory and install command appropriate to your package manager, and confirm that your build environment supports BuildKit. A cache mount is a build-time optimization, not a directory to copy into the runtime stage.

Keep secrets out of the final image

Multi-stage builds do not, by themselves, make secret handling safe. Avoid copying credential-bearing files into a stage that contributes files to a distributable image. Use Docker’s build-secret mechanisms for credentials needed during a build, and follow the cache invalidation guidance: secret contents do not participate in the build cache key. Do not rely on changing a secret alone to force a cached instruction to run again.

Choose a stage layout by what you need to optimize

Compare Dockerfile designs on the outcomes that matter to your application and team, rather than choosing a base image or stage arrangement as a universal best practice.

Decision axis What to examine
Final image contents and size Which build-only tools can be left behind, which runtime files must remain, and the measured size of the image you distribute.
Rebuild time and cache reuse Whether stable inputs are processed before volatile source, and how often changes invalidate expensive steps.
Clarity and reuse Whether named stages make the build easier to understand, and whether shared stages can reduce duplication across targets or related builds.

Docker’s getting-started example displays one resulting image at 428 MB and another at 880 MB. Those are illustrative outputs from that example, not a general benchmark or a saving to expect for your application. See the Docker example.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate the final image before distributing it

After changing the stages or copy paths, check the built runtime image rather than assuming a successful build proves it is complete:

Docker’s build best practices recommend separating build instructions into stages and note that common stages can be reused. The appropriate layout depends on the application and its runtime requirements.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.