Learn Docker · 5/12

Optimizing Docker Images for Speed and Size

9 min read

If you have ever built a Docker image for a simple web app and found out it was 1.5 Gigabytes, you are not alone. It is a rite of passage. If your Docker image is that large to run a 50-line Node.js script, you are casually forcing your servers to download the equivalent of an HD movie just to print "Hello World".

In the industry, large images mean slower deployments, higher cloud storage costs, and a much larger attack surface for security vulnerabilities. Slow build times mean your CI/CD pipelines will take minutes (or hours) instead of seconds, which leads to frustrated engineers.

Let's fix that. In this guide, we will look at how Docker builds images, how to optimize them to be as small as possible, and how to make them build in a fraction of a second.


1. Understanding Docker Image Layers and the Build Cache

The Problem

When you run docker build -t my-app ., Docker executes your Dockerfile from top to bottom. If you change a single typo in a CSS file and rebuild, Docker might re-download your operating system updates, re-install all your project dependencies, and re-compile everything. This wastes a massive amount of time.

The Concept: Image Layers and Build Cache

A Docker image is not a single massive file. It is composed of Layers.
A layer is a read-only set of files and directories generated by a specific instruction (like RUN, COPY, or ADD) in your Dockerfile.

When Docker builds an image, it processes each instruction and saves the resulting layer into a Build Cache on your machine.

If Docker sees that an instruction has not changed, and the files it relies on have not changed, it skips executing that instruction and simply loads the exact same layer from the cache. This is called a cache hit.

Under the hood: Docker uses a storage driver (like overlay2) that stacks these read-only layers on top of each other. When a container runs, Docker simply adds one thin "read-write" layer on the very top of the stack.

How it solves the problem

By ordering our Dockerfile instructions from least frequently changed to most frequently changed, we can force Docker to use the cache for the heavy lifting (like installing dependencies) and only rebuild the final layer (our source code).

Industry Standard Example

Let's look at a common mistake in a Node.js Dockerfile:

❌ The Bad Way:

dockerfile
FROM node:20-alpine
WORKDIR /app
# We copy EVERYTHING into the image, including our source code
COPY . .
# We install dependencies
RUN npm install
CMD ["node", "app.js"]

Why is this bad? Docker checks the COPY . . step. Because you modified index.html (which is part of .), the cache for this step is invalidated. Because this step's cache is busted, every single step below it is also invalidated. npm install will run again, taking 3 minutes to download packages.

✅ The Industry Standard Way:

dockerfile
FROM node:20-alpine
WORKDIR /app

# Step 1: Copy ONLY the package files first
COPY package.json package-lock.json ./

# Step 2: Install dependencies
RUN npm install

# Step 3: Copy the rest of the source code
COPY . .

CMD ["node", "app.js"]

Why is this good? We separated the dependencies from the source code. Now, if you change index.html, Docker sees that package.json did not change. It uses the cache for COPY package.json... and RUN npm install. It only invalidates the cache at COPY . .. Your build time drops from 3 minutes to 0.5 seconds. ⚡


2. Best Practices for Writing Clean, Efficient Dockerfiles

The Problem

Every RUN, COPY, and ADD instruction creates a new layer in your final image. If you download a file, extract it, and then delete the downloaded archive in three separate RUN commands, your final image still contains the deleted archive hidden in the historical layers. The image size continues to bloat.

The Concept: Chaining Commands and Cleanup

To keep layers minimal, industry practice dictates chaining related shell commands together using && within a single RUN instruction. Furthermore, any temporary files or caches created by package managers must be deleted within that exact same RUN instruction before the layer is saved.

How it solves the problem

By doing the setup and cleanup in the same RUN step, the resulting layer only contains the final necessary files. The temporary files never make it into the Docker history.

Real-Life Analogy

Imagine you are building a house (the image), and each instruction is a day of work (a layer).
On Monday (Layer 1), you bring 50 tons of scaffolding to the site.
On Tuesday (Layer 2), you build the walls.
On Wednesday (Layer 3), you dismantle and remove the scaffolding.
If someone looks at the final house, the scaffolding is gone. But because Docker keeps a perfect snapshot of every day's work to build the final product, the scaffolding is forever cemented in Layer 1, weighing down the total delivery. You must bring the scaffolding, build the walls, and remove the scaffolding all on the same day (a single RUN command).

Industry Standard Examples

❌ The Bad Way (Bloated Image):

dockerfile
FROM ubuntu:22.04
# Creates Layer 1 (downloads apt database)
RUN apt-get update 
# Creates Layer 2 (installs curl)
RUN apt-get install -y curl 
# Creates Layer 3 (attempts to clean up, but the bloat is already saved in Layer 1)
RUN rm -rf /var/lib/apt/lists/* 

✅ The Industry Standard Way (Lean Image):

dockerfile
FROM ubuntu:22.04
# One single layer. Updates, installs, and cleans up immediately.
RUN apt-get update && \
    apt-get install -y --no-install-recommends curl && \
    rm -rf /var/lib/apt/lists/*

Note the --no-install-recommends flag. This is a critical industry trick for Debian/Ubuntu base images. It prevents apt from installing hundreds of megabytes of "suggested" packages that you will never use.

Choosing the Right Base Image

Another major practice is changing your FROM statement. Do not use full operating systems if you don't need them.

  • FROM node:20 (Based on Debian, ~1GB size)
  • FROM node:20-slim (Stripped down Debian, ~200MB size)
  • FROM node:20-alpine (Based on Alpine Linux, ~110MB size)

Alpine is incredibly popular because it is a bare-metal Linux distribution designed for security and size.


3. Multi-stage Builds: Keeping Your Final Images Lean

The Problem

Compiled languages like Go, Rust, Java, or C++ require compilers, SDKs, and build tools to turn source code into an executable application. If you install the Go compiler in your Dockerfile to build your app, that entire compiler gets shipped to your production servers. This bloats the image by gigabytes and provides hackers with free development tools if they breach your container.

The Concept: Multi-stage Builds

A multi-stage build is a Docker feature that allows you to use multiple FROM statements in a single Dockerfile. Each FROM statement begins a new "stage" of the build. You can selectively copy files from a previous stage into your current stage, leaving behind everything you do not want.

How it solves the problem

You use a heavy, tool-packed stage to compile your code. Then, you spin up a tiny, empty stage, copy only the compiled executable binary from the first stage, and discard the rest.

Real-Life Analogy

Think of a car factory. The factory contains massive robotic arms, welding tools, and miles of conveyor belts to build the car. When you buy the car, the manufacturer does not ship the entire factory to your driveway. They just ship the finished car. The factory is the builder stage. The car is the final production image.

Industry Standard Example (Go Application)

dockerfile
# ---------------------------------------
# STAGE 1: The "Factory" (Builder Stage)
# ---------------------------------------
FROM golang:1.21-alpine AS builder
WORKDIR /app

# Copy source code and download dependencies
COPY . .
RUN go mod download

# Compile the application into a binary file named 'myapp'
RUN go build -o myapp .

# ---------------------------------------
# STAGE 2: The "Driveway" (Production Stage)
# ---------------------------------------
# We use a completely empty operating system called 'scratch'
FROM scratch 

# We ONLY copy the compiled binary from the 'builder' stage
COPY --from=builder /app/myapp /myapp

# Run the app
ENTRYPOINT ["/myapp"]

By doing this, the final image size goes from ~800MB (the Golang image) to just 5MB (the exact size of the binary itself). No OS, no shell, no compilers. Just the app.


4. Using .dockerignore: Excluding Unnecessary Files

The Problem

Whenever you type docker build ., the very first thing the Docker CLI does is bundle up everything in your current directory (known as the "Build Context") and send it to the Docker Daemon.
If you have a 2GB node_modules folder, a .git directory containing 5 years of version history, or sensitive .env files lying around, Docker uploads all of it. This takes a massive amount of time before the build even starts, and risks copying sensitive passwords into your image.

The Concept: .dockerignore

A .dockerignore file is a plain text file placed in the root of your project. It dictates exactly which files and directories should be excluded from the Docker Build Context. It works exactly like a .gitignore file.

How it solves the problem

When Docker prepares the build context, it checks .dockerignore. Any matched files are completely ignored. They are not sent to the Daemon, and if you run COPY . . in your Dockerfile, those ignored files will not be copied. This saves bandwidth, speeds up the build, and secures your image.

Industry Standard Example

Create a file named .dockerignore right next to your Dockerfile.

Standard .dockerignore for a web application:

text
# Ignore git history
.git
.gitignore

# Ignore dependencies (let Docker install them internally!)
node_modules/
npm-debug.log
venv/
__pycache__/

# Ignore environment variables and secrets
.env
*.pem
secrets.json

# Ignore local markdown docs
README.md
docs/

By adding node_modules to your .dockerignore, you guarantee that your local machine's dependencies don't overwrite the clean dependencies Docker is trying to install inside the container. It is the cheapest, easiest optimization you can make.


🎉 Summary Checklist for Industry Dockerfiles

  1. Use a .dockerignore file to banish node_modules, .git, and .env files.
  2. Pick a smaller base image (alpine or slim).
  3. Copy dependency manifests (package.json, go.mod) first to utilize the Build Cache.
  4. Chain RUN commands with && and clear package manager caches in the same step.
  5. Use Multi-stage builds to strip out build tools and compilers from the final image.

📚 References and Further Reading

Challenge

Dockerfile Optimization Challenge

You are tasked with creating a highly optimized, production-ready Dockerfile for a Node.js web application, along with its corresponding .dockerignore file.

Your goal is to apply best practices to ensure the final image is small, secure, and builds quickly.

Requirements:

  1. Multi-Stage Build:

    • Create a Dockerfile that uses at least two stages: a builder stage and a final production stage.
  2. Builder Stage:

    • Use node:20-alpine as the base image.
    • This stage should install all dependencies, including development dependencies (devDependencies).
  3. Production Stage:

    • Use node:20-alpine as the base image.
    • This stage must not contain any development dependencies or build tools from the previous stage.
    • Copy only the necessary application code and production node_modules from the builder stage.
  4. Cache Optimization:

    • Structure your Dockerfile instructions so that a change in the application's source code does not trigger a re-install of npm dependencies, thus leveraging the build cache.
  5. Build Context:

    • Write the contents of a .dockerignore file. This file must prevent node_modules, the .git directory, and any .env files from being sent to the Docker daemon during the build process.

Expected result

The user must provide the content for two files: a Dockerfile and a .dockerignore file.

Dockerfile

The Dockerfile must implement a multi-stage build.

Stage 1: Builder

  • Must start with FROM node:20-alpine AS builder.
  • Must set a working directory, e.g., WORKDIR /app.
  • Must copy package.json and package-lock.json (COPY package*.json ./).
  • Must run RUN npm install to install all dependencies.
  • Must copy the rest of the application source code afterwards, e.g., COPY . ..

Stage 2: Production

  • Must start with a new, minimal base image: FROM node:20-alpine.
  • Must set a working directory, e.g., WORKDIR /app.
  • Must copy only the production dependencies from the builder stage using COPY --from=builder /app/node_modules ./node_modules.
  • Must copy the application source code from the builder stage, e.g., COPY --from=builder /app ..
  • Should expose the application port, e.g., EXPOSE 3000.
  • Must define the command to run the application, e.g., CMD ["node", "server.js"].

.dockerignore

The file content must include at least the following entries, each on a new line:

  • node_modules
  • .git
  • .env
dockerfile

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.