.dockerignore and image size
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ShopLite build sends 133 MB to Docker before it runs a single instruction, and a forgotten .env file can end up inside the image. Controlling what Docker may see fixes both problems.
The build context
The build context is every file in the folder you name at the end of docker build (usually .). Docker packs these files and sends them to the builder before it runs the first instruction.
Example 1 builds ShopLite and prints a long transferring context line. Most of the 133 MB it sends is files the build never uses.
Example 1 · A slow build that sends 133 MB of context
Runs in: a terminal with Docker installed
# shoplite-api with no .dockerignore: target/, .git and logs/ are all sentdocker build -t shoplite-api:1.2.0 .# the same build after adding .dockerignoredocker build -t shoplite-api:1.2.0 .[+] Building 47.3s (16/16) FINISHED docker:desktop-linux => [internal] load build definition from Dockerfile 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [internal] load build context 24.8s => => transferring context: 133.31MB 24.6s ... [+] Building 3.1s (16/16) FINISHED docker:desktop-linux => [internal] load .dockerignore 0.0s => => transferring context: 214B 0.0s => [internal] load build context 0.1s => => transferring context: 21.62kB 0.0s ...
What this code does
- The first build has an empty
.dockerignore(2 bytes), soload build contextsends 133 MB before any instruction runs. - With a
.dockerignorethe context is about 21 kB: onlypom.xml,mvnw,.mvnandsrc. Your sizes and times will differ.
The builder can only COPY files from the context, so the context is sent first. But Docker does not know which files you will copy, so by default it sends everything: target/ with old jars, the whole .git history, IDE folders and log files.
On a laptop this shows up as a slow build. With a remote builder or in CI, those megabytes travel over the network on every build.
docker build -f docker/Dockerfile . still sends the whole current folder..dockerignore for a Maven project
A .dockerignore is a file next to the Dockerfile, in the top folder of the context, that lists paths Docker must leave out. It works like .gitignore: one pattern per line, # for comments and ! to bring a path back.
The .dockerignore for ShopLite is below. Each line names something the image build does not need.
# .dockerignore for shoplite-apitarget/.git.gitignore.idea**/*.iml.vscode**/.env*.env!.env.examplelogs**/*.logDockerfile.dockerignoreExample 2 · Which files enter the build context
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.regex.Pattern;
class DockerIgnore { private final List<Pattern> rules = new ArrayList<>();
DockerIgnore(List<String> lines) { for (String line : lines) { String p = line.trim(); if (p.isEmpty() || p.startsWith("#")) { continue; } if (p.endsWith("/")) { p = p.substring(0, p.length() - 1); } rules.add(Pattern.compile(toRegex(p))); } }
// A small model of .dockerignore globs: * and ? stay inside one folder, **/ means "any folders". static String toRegex(String glob) { StringBuilder rx = new StringBuilder(); for (int i = 0; i < glob.length(); i++) { char c = glob.charAt(i); if (glob.startsWith("**/", i)) { rx.append("(.*/)?"); i += 2; } else if (c == '*') { rx.append("[^/]*"); } else if (c == '?') { rx.append("[^/]"); } else { rx.append(Pattern.quote(String.valueOf(c))); } } return rx.toString(); }
// A file is ignored when a rule matches the file itself or one of its parent folders. boolean ignores(String path) { String current = path; while (true) { for (Pattern rule : rules) { if (rule.matcher(current).matches()) { return true; } } int slash = current.lastIndexOf('/'); if (slash < 0) { return false; } current = current.substring(0, slash); } }}
public class BuildContextDemo { public static void main(String[] args) { Map<String, Integer> project = new LinkedHashMap<>(); // path -> size in KB project.put("pom.xml", 6); project.put("mvnw", 11); project.put(".mvn/wrapper/maven-wrapper.properties", 1); project.put("src/main/java/com/shoplite/ShopliteApiApplication.java", 1); project.put("src/main/resources/application.yml", 2); project.put("target/shoplite-api-1.2.0.jar", 61_440); project.put(".git/objects/pack/pack-1f3a.pack", 48_128); project.put(".idea/workspace.xml", 96); project.put("shoplite-api.iml", 14); project.put(".env", 1); project.put("logs/shoplite.log", 20_480);
DockerIgnore ignore = new DockerIgnore(List.of( "target/", ".git", ".idea", "*.iml", ".env", "logs"));
int sent = 0; int total = 0; for (Map.Entry<String, Integer> file : project.entrySet()) { boolean skip = ignore.ignores(file.getKey()); System.out.printf("%-5s %s%n", skip ? "skip" : "send", file.getKey()); total += file.getValue(); if (!skip) { sent += file.getValue(); } } System.out.println("Context without .dockerignore: " + total + " KB"); System.out.println("Context with .dockerignore: " + sent + " KB"); }}send pom.xml send mvnw send .mvn/wrapper/maven-wrapper.properties send src/main/java/com/shoplite/ShopliteApiApplication.java send src/main/resources/application.yml skip target/shoplite-api-1.2.0.jar skip .git/objects/pack/pack-1f3a.pack skip .idea/workspace.xml skip shoplite-api.iml skip .env skip logs/shoplite.log Context without .dockerignore: 130180 KB Context with .dockerignore: 21 KB
What this code does
- This is a small model of
.dockerignore, not Docker's real code: a rule ignores a file when it matches the file or one of its parent folders, sotarget/skips everything undertarget. - The jar, the Git pack file and the log decide the size. Leaving them out takes the context from about 127 MB to 21 KB.
.envis skipped too. That matters more than the size, as the next section shows.
Example 3 · The top-folder trap: .iml vs /.iml
import java.util.List;import java.util.regex.Pattern;
public class IgnoreDepthDemo { // Same small glob model: * stays inside one folder, **/ means "any folders, or none". static boolean matches(String glob, String path) { String rx = glob.replace(".", "\\.") .replace("**/", "\u0000") .replace("*", "[^/]*") .replace("\u0000", "(.*/)?"); return Pattern.matches(rx, path); }
public static void main(String[] args) { List<String> paths = List.of( "shoplite-api.iml", "admin-tools/admin-tools.iml", ".env", "docker/.env");
for (String glob : List.of("*.iml", "**/*.iml", ".env", "**/.env")) { System.out.println("Pattern " + glob); for (String path : paths) { if (matches(glob, path)) { System.out.println(" ignores " + path); } } } }}Pattern *.iml ignores shoplite-api.iml Pattern **/*.iml ignores shoplite-api.iml ignores admin-tools/admin-tools.iml Pattern .env ignores .env Pattern **/.env ignores .env ignores docker/.env
What this code does
*.imland.envmatch only in the top folder of the context, so the files inadmin-tools/anddocker/would still be sent.- Starting the pattern with
**/matches the name in every folder, including the top one. That is why the.dockerignoreabove uses**/*.imland**/.env.
For a Spring Boot Maven project the usual list is target/ (the multi-stage build makes its own jar), .git, .idea and *.iml, .env and logs. Ignored files do not exist for COPY, so they can never end up in the image by accident.
One rule differs from .gitignore: a pattern without a folder matches only at the top. *.iml ignores shoplite-api.iml but not admin-tools/admin-tools.iml. Write **/*.iml to match in every folder.
Predict the output
Is the file sent to Docker?
Read the .dockerignore, then decide for the file.
Round 1 of 3
Is admin-tools/admin-tools.iml left out of the context?
Secrets leak through COPY . .
A whiteout is the "deleted" marker that a later layer adds when a file is removed. The file itself stays in the lower layer, so RUN rm .env hides a secret but does not remove it from the image.
Example 4 shows a deleted file still living in a lower layer. Example 5 then finds a leaked .env in a real image.
Example 4 · A deleted file still lives in a lower layer
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
class Layer { final String instruction; final Map<String, String> files = new LinkedHashMap<>(); // path -> content, null = deleted here
Layer(String instruction) { this.instruction = instruction; }}
public class LayerLeakDemo { // What a running container sees: later layers win, a deletion hides the file. static Map<String, String> containerView(List<Layer> image) { Map<String, String> view = new LinkedHashMap<>(); for (Layer layer : image) { layer.files.forEach((path, content) -> { if (content == null) { view.remove(path); } else { view.put(path, content); } }); } return view; }
public static void main(String[] args) { List<Layer> image = new ArrayList<>();
Layer copy = new Layer("COPY . ."); copy.files.put("app.jar", "<61 MB of bytecode>"); copy.files.put(".env", "DB_PASSWORD=Shoplite@Prod#2026"); image.add(copy);
Layer remove = new Layer("RUN rm .env"); remove.files.put(".env", null); // a "whiteout" marker, not a real delete image.add(remove);
System.out.println("Inside the container: " + containerView(image).keySet()); System.out.println("Layers anyone with the image can unpack:"); for (Layer layer : image) { System.out.println(" " + layer.instruction + " -> " + layer.files); } }}Inside the container: [app.jar]
Layers anyone with the image can unpack:
COPY . . -> {app.jar=<61 MB of bytecode>, .env=DB_PASSWORD=Shoplite@Prod#2026}
RUN rm .env -> {.env=null}What this code does
- Each layer stores only its own changes.
RUN rm .envstores a deletion marker (Docker calls it a whiteout), so the running container no longer sees.env. - The
COPY . .layer is unchanged and ships with the image. Unpacking it gives back the password, as the next example shows with real Docker commands.
Example 5 · Finding the leaked .env in a real image
Runs in: a terminal with Docker installed
# Dockerfile of shoplite-api:leaky (no .dockerignore):# FROM eclipse-temurin:25-jre# WORKDIR /app# COPY . .# RUN rm -f .env# ENTRYPOINT ["java", "-jar", "target/shoplite-api-1.2.0.jar"]docker run --rm --entrypoint ls shoplite-api:leaky -a /appdocker save shoplite-api:leaky -o leaky.tarmkdir leaky && tar -xf leaky.tar -C leakyfor layer in leaky/blobs/sha256/*; do tar -tf "$layer" 2>/dev/null | grep -E "^app/(\.wh\.)?\.env$" && echo " in $layer"done. .. .env.example .git .gitignore .idea .mvn logs mvnw pom.xml src target app/.env in leaky/blobs/sha256/6f0c2b8e41d7... app/.wh..env in leaky/blobs/sha256/b93a7d05c2e1...
What this code does
- Inside the container
.envis gone, but.git,.idea,logsandtargetwere all copied in. - The saved image still holds
app/.envin theCOPY . .layer; the next layer only adds the whiteout fileapp/.wh..env. Layer ids will differ on your machine.
So COPY . . without a .dockerignore copies your real .env into a layer. Anyone who can pull the image can save it with docker save, unpack the layers and read the password, whether or not a later step deleted it.
The fix is to make sure the file never reaches the builder: list .env in .dockerignore, copy only what you need (COPY pom.xml, COPY src src), and pass secrets at run time with -e or --env-file.
Find the bug
Find the leak
Tap the line that puts the secret into the image.
The Dockerfile deletes .env at the end. Which line leaks it?
Round 1 of 2Measuring: docker images and docker history
Build three versions of the ShopLite Dockerfile with the tags v1, v2 and v3, then compare their sizes.
Example 6 · Comparing three Dockerfile versions
Runs in: a terminal with Docker installed
# v1: one stage on a JDK, COPY . ., no .dockerignore# v2: multi-stage, eclipse-temurin:25-jre, .dockerignore# v3: v2 on eclipse-temurin:25-jre-alpine with Spring Boot layersdocker images shoplite-apidocker history shoplite-api:v1REPOSITORY TAG IMAGE ID CREATED SIZE shoplite-api v3 5d1e7a9c3b20 12 seconds ago 247MB shoplite-api v2 a83f6c21d4e9 3 minutes ago 331MB shoplite-api v1 e7b90d4c1f56 9 minutes ago 874MB IMAGE CREATED CREATED BY SIZE COMMENT e7b90d4c1f56 9 minutes ago CMD ["java" "-jar" "target/shoplite-api-1.2… 0B buildkit.dockerfile.v0 <missing> 9 minutes ago RUN /bin/sh -c ./mvnw -B package -DskipTest… 236MB buildkit.dockerfile.v0 <missing> 9 minutes ago COPY . . # buildkit 134MB buildkit.dockerfile.v0 <missing> 9 minutes ago WORKDIR /app 0B buildkit.dockerfile.v0 <missing> 3 weeks ago /bin/sh -c #(nop) ENTRYPOINT ["/__cacert_en… 0B ...
What this code does
docker historypoints at the culprits in v1:COPY . .added 134 MB (old jars,.git, logs) and the Maven run added 236 MB (the~/.m2downloads plus a newtarget/).- v2 drops both with a multi-stage build and a JRE. v3 saves a little more with a smaller Alpine base. Exact sizes depend on versions and CPU type.
docker images lists your images with their total size. docker history <image> lists the layers of one image, newest first, with the instruction that made each layer and its size.
Measure before you optimise. docker history shows which instruction added the megabytes, so you fix the right line.
Size tips that matter
jlink is a JDK tool that builds a custom Java runtime holding only the JDK modules your app uses. The jdeps tool lists those modules.
A few choices decide most of an image's size. Everything else saves only a few megabytes.
- Matters a lot: run on a JRE image, not a JDK (often 150 MB or more saved).
- Matters a lot: multi-stage builds, so Maven,
~/.m2, the source andtarget/stay in the build stage. - Matters: a
.dockerignore, and a smaller base such as an Alpine JRE when your app works on it. - Matters little: joining tiny RUN lines, deleting docs, or squeezing a few KB out of
application.yml.
jlink can save tens of megabytes more, but a missing module shows up only when that code runs, so test well. Most student projects stop at a JRE image.
Next step
Check your understanding
12 quick questions