Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober 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 Now×
Skip to content
World desk4 min

Lean Docker Images: Multi-Stage Builds and Layer Caching

Multi-stage builds keep compilers out of runtime images; cache-aware ordering speeds repeat builds. Learn how to handle context and freshness, too.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To make a Docker image smaller, build the application in one stage and copy only its runtime artifacts into the final stage. To make repeat builds faster, order instructions so stable inputs—especially dependency manifests—are handled before frequently changing source files. These techniques solve different problems: stages control what ships, while the build cache controls what work can be reused.

How multi-stage builds keep build tools out of the runtime image

A multi-stage Dockerfile has multiple FROM instructions. Each starts a new stage; a later stage can copy selected files from an earlier one. Unless you specify a build target, Docker produces the final stage as the image. See Docker’s multi-stage build guide.

Use an earlier stage for compilers, package managers, development dependencies, and other tools needed to produce the application. Then create a final stage from a runtime-appropriate base and copy in only the executable, production assets, and other files the running program needs. This reduces the chance that build-only tools and files become part of the deployable image.

A smaller base is not automatically a suitable base. The final image still needs the program’s language runtime, shared libraries, certificates, and operating-system compatibility as applicable. Verify what the application needs rather than choosing a base solely for its footprint. Docker discusses small runtime images and stage separation in its cloud build optimization guide.

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.

Example: compile, then copy the artifact

This schematic Dockerfile shows the structure, not a universal recipe. Replace the commands and paths with those required by your language, package manager, and application.

FROM build-image AS build
WORKDIR /src
COPY . .
RUN build-command

FROM runtime-image
WORKDIR /app
COPY --from=build /src/output/app ./app
CMD ["./app"]

The first stage can contain tools needed for build-command; the final stage receives only the selected output. If the program also requires configuration, static assets, or shared libraries, include those deliberately. A multi-stage build does not discover runtime requirements for you.

How Docker layer caching affects repeat builds

Docker processes Dockerfile instructions in order and reuses a result when the instruction and relevant inputs match the cache. If a layer cannot be reused, subsequent layers must be rebuilt. The details matter: for COPY and ADD, Docker considers file metadata, but modification time alone is not part of the cache checksum. For an ordinary RUN, Docker checks the command string rather than whether a remote repository has changed. See Docker’s cache invalidation guide.

That means a cached RUN apt-get update is not inherently a fresh package update. Cache reuse is a build-speed mechanism, not a package-freshness guarantee.

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

Put stable dependency inputs before changing source

When the project’s package manager permits it, copy dependency manifests and lockfiles first, install dependencies, and then copy the rest of the source. If only application code changes, Docker may be able to reuse the dependency-installation result. If a manifest or lockfile changes, the dependency step needs to run again.

For example, Docker’s Node guidance uses this general sequence: copy package manifests and a lockfile, install dependencies, then copy the remaining application files. Adapt the pattern to your language and package manager; it is not a drop-in template for every project. See Using the build cache.

Keep irrelevant files out of the build context

A .dockerignore file excludes matching files from the build context sent to the builder. Common candidates include .git, generated build outputs, and dependency directories that are restored during the build. Docker’s building best practices explains context exclusions; its cloud optimization guide covers why context size matters for remote builds.

Exclusions should match how the build works. For example, if you omit .git, commands inside the build cannot read Git metadata unless another mechanism provides it. Excluding a dependency directory is appropriate when dependencies are installed within the image build, but not if the build relies on that directory being present in the context.

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

This is only an example: exclude generated paths that your own build can recreate, and retain every input it actually needs. A smaller context can reduce unnecessary transfer to a remote builder as well as local processing.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose cache reuse or freshness deliberately

Two build options have separate jobs. Docker documents --no-cache as a way to rerun build steps without using the build cache, while --pull fetches a fresh base image. Use them together when you want both actions; neither flag should be mistaken for the other. See Docker’s best practices.

  • docker build --no-cache -t app:local . reruns build steps rather than reusing cached results.
  • docker build --pull -t app:local . checks for a fresh base image while still allowing build-step caching.
  • docker build --pull --no-cache -t app:local . requests both a fresh base image and uncached build steps.

Choose based on the change you need. Reusing cache favors speed when inputs have not changed; refreshing base images or rerunning package-install steps is a separate freshness decision.

What BuildKit can—and cannot—promise

Docker documents BuildKit capabilities that include skipping unused stages, parallelizing independent stages, and incrementally transferring changed context files. These can help in appropriate workflows, but they do not guarantee a particular speedup for every Dockerfile or project. The final result still depends on the build graph, inputs, cache availability, and context. See Docker BuildKit documentation.

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

Which change should you make first?

Your priority Start with Trade-off to check
Smaller runtime image Use a build stage for tools, then copy required artifacts into a runtime stage. The final base must still provide the application’s runtime and libraries.
Faster repeat builds Separate stable dependency manifests and installation from frequently changing source. Changes to dependency inputs still invalidate the dependency-installation result.
Less context transfer Exclude irrelevant files with .dockerignore. Excluded files are unavailable to commands in the build context.
Fresh packages or base image Use --no-cache for build steps and/or --pull for the base image. Freshness can require work that cache reuse would otherwise avoid.

For a practical sequence, first separate build-time tools from runtime contents, then arrange dependency inputs ahead of volatile source, and finally trim the context without excluding required inputs. Treat image contents, cache reuse, and dependency freshness as distinct controls rather than expecting one Dockerfile trick to solve all three.

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.

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.