Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 15

    Docker Image Layers, the Build Cache and .dockerignore for .NET

    Docker image layers, the build cache and .dockerignore make .NET builds faster by reusing unchanged work and keeping unrelated files out of the build.

    The biggest improvement is often simple: copy the files needed for restore first, restore packages, and only then copy application source. A source edit can then reuse the restore step instead of downloading and resolving packages again.

    This lesson builds on images vs containers. Here, we will follow what Docker saves, what makes it repeat work, and how to check whether your changes helped.

    How do Docker image layers work?

    A filesystem layer records changes to files and folders. An image is a pile of read-only layers. Docker places each layer on top of the one before it and shows them together as one set of files. A file in a higher layer hides the same file in a lower one. Images can share layers rather than storing another copy of identical underlying layers. A running container adds its own writable layer above them.

    flowchart TD
        A["Base image layers"] -->|"underlie"| B["Application layers"]
        B -->|"underlie"| C["Container writable layer"]

    The container sees the combined files, while its writes belong to the writable layer.

    RUN executes a build command, and COPY and ADD bring files into the image (when to use ADD). These instructions can create filesystem layers. By contrast, ENV sets environment variables and ENTRYPOINT sets the startup command; these change image settings rather than adding application files.

    After building the example later in this lesson, inspect its history:

    Shell
    docker image history --no-trunc cache-demo

    History shows build instructions and their recorded sizes. For example, these illustrative rows are abbreviated and have made-up sizes; your output will differ:

    Text
    CREATED BY                         SIZE
    ENTRYPOINT ["dotnet", "/out/App.dll"]  0B
    RUN dotnet restore App.csproj       120MB
    COPY App.csproj ./                 1kB
    ENV DOTNET_RUNNING_IN_CONTAINER=true  0B

    In a real app with many NuGet packages, the restore row can be large; this small sample has no package references, so its restore row is small. Settings-only entries can show 0B; a history row is not necessarily a separate filesystem layer containing files.

    Deletion is also recorded as a change. If one instruction copies secret.txt and a later RUN deletes it, the combined filesystem hides the file. The earlier layer still retains its bytes. The deletion does not make the image smaller, and anyone who has the image can still extract the secret from the earlier layer.

    The mistake to avoid. Do not treat a later deletion as an eraser for earlier layers. Never copy build credentials into layers; use build-secret mounts, which make a secret available to a build command without an ordinary COPY. See the image security lesson for the full approach.

    In an interview, say: “Images stack read-only filesystem changes that can be shared between images. Containers add a writable layer. RUN, COPY and ADD can create filesystem layers; ENV and ENTRYPOINT change settings. Deleting a file later does not remove its bytes from an earlier layer.”

    What invalidates Docker's build cache?

    The builder is the component that executes Dockerfile instructions. Its build cache stores reusable results from earlier builds. A cache hit means the builder can reuse a result instead of executing that work again.

    The build context is the set of local files made available to a build. In this command, the final dot selects the current folder as the context:

    Shell
    docker build --progress=plain -t cache-demo .

    For each step, Docker considers the instruction and its relevant inputs. Changing a RUN command can cause a miss. Changing files selected by COPY can also cause a miss. Docker compares each file's contents and details such as its name and permissions. A changed modification time alone does not cause a miss.

    A miss also affects work that depends on that result. In a simple sequence, changing copied source makes the later publish step run again. It does not mean every instruction anywhere in a more complex build must rebuild: independent work can remain reusable.

    For an ordinary RUN, Docker does not check whether a remote package feed has changed. If the command and its build dependencies still match, it can reuse the old result without contacting that feed.

    These switches serve different purposes:

    Shell
    docker build --no-cache -t cache-demo .
    docker build --pull -t cache-demo .

    --no-cache prevents reuse of cached build-step results. It does not by itself fetch a newer base image. --pull attempts to fetch newer versions of referenced images. Combine them when you need both behaviours.

    The mistake to avoid. A cache hit means matching build inputs, not “the internet still contains the same packages.” Refreshing remote dependencies requires an intentional rebuild policy.

    In an interview, say: “Instruction changes or changes to relevant inputs cause cache misses and invalidate dependent work. COPY checks contents and relevant metadata, not modification time alone. Remote package changes do not automatically invalidate RUN. No-cache rebuilds steps; pull checks for newer base images.”

    How should a .NET Dockerfile reuse dotnet restore?

    dotnet restore resolves package dependencies and downloads missing packages. It also produces files under obj that later build commands use. Microsoft's restore reference explains its inputs and options.

    If you put COPY . . before restore, a source edit changes the copied input to the restore step. Docker must then reconsider work that did not actually need the changed source.

    Instead, separate files by how often they change:

    flowchart TD
        A["Copy restore inputs"] -->|"supplies inputs to"| B["Restore packages"]
        B -->|"provides dependencies for"| C["Copy source and publish"]

    This ordering lets source changes reuse a restore result when its inputs have not changed.

    For a small experiment, create a console project with dotnet new console -n App --framework net10.0. Work inside its App folder. Save this as Dockerfile, and add the .dockerignore from the next section before building.

    FROM picks the base image the build starts from, and WORKDIR sets the folder the later instructions work in.

    Dockerfile
    FROM mcr.microsoft.com/dotnet/sdk:10.0
    WORKDIR /src
    
    COPY ["App.csproj", "./"]
    RUN dotnet restore App.csproj
    
    COPY . .
    RUN dotnet publish App.csproj -c Release --no-restore -o /out
    
    ENTRYPOINT ["dotnet", "/out/App.dll"]

    Build it with the earlier docker build command. You can run it with docker run --rm cache-demo.

    The first COPY supplies the project file. Restore saves its results. The second COPY supplies source files. Publish uses --no-restore to avoid the implicit restore it would otherwise perform.

    For a real solution, the first group must include all restore inputs, not just the application project. Include every referenced project file, preserving its directory structure. Also include the solution file when you restore a solution (.sln, or .slnx, which dotnet new sln creates by default in the .NET 10 SDK), and applicable global.json, NuGet.Config, Directory.Build.props, Directory.Build.targets, Directory.Packages.props, lock files and custom imported files. Only add explicit COPY instructions for files that exist in your repository.

    This example deliberately keeps the SDK and build files in the image so you can inspect the sequence. It is not a production image recipe. Continue with multi-stage ASP.NET Core Dockerfiles, which separate build tools from the final application image. Microsoft's container tutorial and .NET Docker samples provide further examples.

    The mistake to avoid. Copying only the main .csproj is insufficient when restore depends on other projects or shared configuration. Missing inputs can break restore or make the cached result unsuitable for the later build.

    In an interview, say: “Copy project files and all other restore inputs first, restore, then copy source and publish with no-restore. That keeps source-only changes from invalidating restore. A fresh builder also needs access to a previously saved cache; ordering alone cannot create a cache hit.”

    What should a .NET .dockerignore exclude?

    A .dockerignore file filters the local build context before files are sent to the builder. A smaller context reduces transfer work and prevents excluded files from changing ordinary COPY inputs.

    Place this starting example beside the sample Dockerfile:

    dockerignore
    **/bin
    **/obj
    .git
    .env
    .env.*
    **/*.pfx
    **/*.key
    **/secrets.json
    *.md
    !README.md

    The **/bin and **/obj patterns cover those folders at different directory depths. Excluding them keeps host build outputs out of the image. This matters especially for obj: the later COPY . . must not overwrite container restore outputs with files generated on your computer.

    The remaining rules exclude repository metadata and some common secret-file locations. These are examples, not a complete inventory of your repository's secrets.

    A rule starting with ! is an exception that includes matching files again. Here, Markdown files in the context root are excluded, but README.md is included again. To exclude Markdown files in every folder, write **/*.md. When rules conflict, the last matching rule determines the result. You can remove both Markdown rules if you want all those files included.

    Docker also supports a separate ignore file for a particular Dockerfile. For build.Dockerfile, name it build.Dockerfile.dockerignore and place it alongside that Dockerfile. It takes precedence over the context-root .dockerignore; do not assume the two lists are combined.

    The mistake to avoid. .dockerignore is not a complete secret safeguard. It only filters context files, and a different context or ignore file can change that protection. Review what your build copies, and keep credentials out of ordinary image inputs.

    In an interview, say: “Dockerignore filters the local build context, reducing transfers and unnecessary COPY cache misses. I exclude bin, obj, repository metadata and secret files. Host obj files can overwrite container restore outputs. Ignore rules help, but they do not replace proper secret handling.”

    Why combine apt-get update, install and cleanup?

    On Debian- or Ubuntu-based images, apt-get update refreshes the package indexes used to find available packages. apt-get install then uses those indexes to install a package.

    Putting them in separate RUN instructions can reuse an old cached update while a changed install command runs against stale indexes. Keep the related work together:

    Dockerfile
    RUN apt-get update \
        && apt-get install -y --no-install-recommends ca-certificates \
        && rm -rf /var/lib/apt/lists/*

    This is a Dockerfile fragment for a compatible Linux base image. The && operators stop the sequence if an earlier command fails. --no-install-recommends avoids installing packages that are only recommended. The final command removes downloaded package indexes before this instruction's filesystem changes are saved.

    Cleanup in a later layer would hide those indexes without removing their bytes from the earlier layer. Combining the commands also does not guarantee fresh packages on every build: the entire RUN can still be cached.

    The mistake to avoid. Combining update and install fixes the stale-index split, not your refresh policy. Decide when to rebuild that step, and use --pull separately when you also need to check the base image.

    In an interview, say: “I combine apt-get update, install and cleanup in one RUN. That prevents a separately cached update from supplying old indexes, and it avoids keeping those indexes in an earlier layer. The combined RUN still needs an intentional refresh policy.”

    How do NuGet cache mounts differ from cached layers?

    BuildKit is Docker's modern build engine. A cache mount gives a build command a reusable working folder whose contents are kept outside the image layers.

    For NuGet, mounting /root/.nuget/packages can retain downloaded packages when restore has to run again. This saves downloads even when Docker cannot reuse the restore step itself.

    Restore writes dependency information, including the list of packages, into obj. The packages themselves go to the global packages folder, /root/.nuget/packages, which here is the mount.

    This split version demonstrates the problem. These four lines would replace the two copy-and-build groups in the earlier Dockerfile:

    Dockerfile
    COPY ["App.csproj", "./"]
    RUN --mount=type=cache,target=/root/.nuget/packages dotnet restore App.csproj
    COPY . .
    RUN dotnet publish App.csproj -c Release --no-restore -o /out

    For a project that needs those downloaded packages, publish fails even on the first build: its RUN does not mount the package folder. The restore files in obj are present, but the packages they name are not available.

    Even mounting the same folder during publish is not a complete fix. A cached restore layer can retain obj after the separately managed package cache has been emptied or removed. Publish with --no-restore cannot download the missing packages.

    The earlier Dockerfile avoids this trap by keeping restored packages in ordinary layers. Another approach is to copy source first, then restore and publish together using the mount. For the sample, this fragment replaces the two copy-and-build groups:

    Dockerfile
    COPY . .
    RUN --mount=type=cache,target=/root/.nuget/packages \
        dotnet restore App.csproj \
        && dotnet publish App.csproj -c Release --no-restore -o /out

    When this command executes, restore can refill missing packages before publish needs them. A source change now reruns the combined command, but the mount can save package downloads.

    The mistake to avoid. A cached layer and a package cache mount have different lifetimes. Do not assume that reusing restore's layer proves the mount still contains every package.

    In an interview, say: “A NuGet cache mount retains downloads outside image layers, helping when restore reruns. Its contents may be absent even when restore is cached. I either keep packages in layers or restore and publish together with the mount, so missing packages can be fetched.”

    How can you check cache reuse and speed up CI builds?

    Use --progress=plain to read individual build steps. Build the sample twice, change only Program.cs, and build again. Then change a restore input, such as the project file, and repeat.

    These are typical abbreviated lines, not a fixed transcript or timing promise:

    Text
    Unchanged build:
    [4/6] RUN dotnet restore App.csproj
    CACHED
    [6/6] RUN dotnet publish App.csproj -c Release --no-restore -o /out
    CACHED
    
    Source-only change:
    [4/6] RUN dotnet restore App.csproj
    CACHED
    [6/6] RUN dotnet publish App.csproj -c Release --no-restore -o /out
    DONE ...
    
    Project/package-input change:
    [4/6] RUN dotnet restore App.csproj
    DONE ...
    [6/6] RUN dotnet publish App.csproj -c Release --no-restore -o /out
    DONE ...

    CACHED means Docker reused the result; it does not mean restore ran unusually quickly. A changed restore input makes restore execute again, but NuGet might still find the needed packages locally.

    Continuous integration (CI) builders often start with an empty cache. BuildKit can export the build cache to a registry with --cache-to and import it with --cache-from; the registries and CI builds lesson shows the full command and the builder setup it needs.

    The mistake to avoid. Do not compare a cold build with a warm build and attribute the whole difference to a Dockerfile edit. Compare matching changes with known cache states, and inspect which steps actually executed.

    In an interview, say: “I use good layer order: restore inputs first, then source, with a focused dockerignore. BuildKit cache mounts can reuse NuGet downloads when restore reruns. Fresh CI builders may have no local cache, so I export and import the build cache with --cache-to and --cache-from.”

    Check yourself

    A Dockerfile copies restore inputs, runs restore, copies source, then publishes with --no-restore. Only Program.cs changes, and the previous build cache is available. What should normally happen?

    A Restore is reused, while the source copy and the publish step execute again.
    B Restore and publish are both reused, as Program.cs is not a project file.
    C Every step runs again, since one changed file invalidates the whole build cache.
    D Restore runs again because the source changed, but publish reuses its cached layer.
    Show answer

    Correct answer: A

    Program.cs is not an input to the early restore group. It changes the later source copy, so publish depends on a changed result.

    Restore used a NuGet cache mount. Its image-layer result is available, but the mount's package contents are missing. What is the safest conclusion about a later publish --no-restore?

    A Publish may fail; keep packages in layers, or run restore before publish with the mount available.
    B BuildKit refills the cache mount from the cached restore layer, so publish can still find the packages.
    C Publish succeeds, because the cached restore layer also stores the mount's package files.
    D Copying the host's bin and obj folders into the build context lets publish find the packages.
    Show answer

    Correct answer: A

    Restore output files and mounted package downloads are stored separately. Reusing the former does not guarantee the latter are present.

    Going deeper

    Restore and publish must agree on package-selection inputs. For example, if publish targets a particular operating system and architecture, restore must produce suitable dependency information for that target. Configuration-dependent package references also need matching settings. --no-restore skips work; it does not repair a mismatch.

    Keep repeatability separate from cache reuse. A cached command preserves an earlier result, while rerunning a command against changing package feeds can produce a different result. Lock files and controlled dependency versions help manage that difference, but neither replaces a deliberate update policy.

    Finally, build-cache storage and image storage are related but different concerns. Exporting build cache can make CI faster without making all intermediate build files part of the application image. Use the dedicated multi-stage and CI lessons to choose what you ship and what you retain only to accelerate builds.

    Sources

    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 30 Nov 2026 ·