Home DockerDockerfile Best Practices: Build Smaller, Faster Images

Dockerfile Best Practices: Build Smaller, Faster Images

by Knowledge Base Linux
Dockerfile best practices illustrated with stacked image layers

Your Docker image is 1.2 GB, builds take ten minutes, and every small code change triggers a full rebuild. Sound familiar? Most of these problems come from the Dockerfile itself. Applying proven dockerfile best practices can shrink images by 80–90%, cut build times dramatically, and reduce your attack surface at the same time. This guide walks through the techniques that matter most in production, with a complete example at the end. If you have not installed Docker yet, start with our guide on how to install Docker on Ubuntu 24.04 first.

Prerequisites – Dockerfile Best Practices

  • A Linux server or workstation with Docker Engine 24 or later
  • Basic familiarity with building images using docker build
  • A sample application to containerize (we use a small Go program in the examples)
Multi-stage builds as part of Dockerfile best practices

1. Choose a Small Base Image – Dockerfile Best Practices

The base image is the foundation of every layer that follows, so it has the biggest impact on final size. The full ubuntu or node images ship with compilers, documentation and dozens of utilities your app never uses. Prefer slim or Alpine variants:

# Heavy: ~1.1 GB
FROM node:20

# Better: ~180 MB
FROM node:20-slim

# Even smaller: ~130 MB
FROM node:20-alpine

Alpine images are tiny but use musl libc instead of glibc. Most applications work fine, yet some native modules expect glibc — always test before switching. For compiled languages such as Go or Rust, you can go further and use scratch or a distroless image as the final base, which contains nothing but your binary.

2. Order Instructions for Layer Caching

Docker builds an image as a stack of layers and caches each one. As soon as a layer changes, that layer and every layer after it are rebuilt. One of the most impactful dockerfile best practices is ordering instructions from least to most frequently changed: copy dependency manifests first, install dependencies, and only then copy your source code.

FROM node:20-alpine
WORKDIR /app

# Dependencies change rarely -> cached layer
COPY package.json package-lock.json ./
RUN npm ci --omit=dev

# Source code changes often -> last layer
COPY . .
CMD ["node", "server.js"]

With this order, editing application code does not invalidate the expensive dependency-install layer, so rebuilds drop from minutes to seconds.

3. Use Multi-Stage Builds

Multi-stage builds let you compile inside a full toolchain image but ship only the result. Build tools, caches and source files stay behind in the builder stage and never reach production.

# ---- Build stage ----
FROM golang:1.22-alpine AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /app/server ./cmd/server

# ---- Final stage ----
FROM alpine:3.20
RUN adduser -D appuser
USER appuser
COPY --from=builder /app/server /usr/local/bin/server
EXPOSE 8080
ENTRYPOINT ["server"]

The builder image is over 300 MB; the final image here is roughly 25 MB. Smaller images pull faster, deploy faster and contain far fewer packages that could carry vulnerabilities.

4. Add a .dockerignore File

Without a .dockerignore, the build context may include .git, node_modules, logs and local secrets — slowing every build and potentially leaking files into the image via a broad COPY . ..

.git
node_modules
*.log
.env
dist
coverage
Dockerfile
docker-compose.yml

Keep the context minimal. This alone often cuts build-context upload time from tens of seconds to almost nothing on remote builders.

5. Combine RUN Commands and Clean Up in the Same Layer

Files deleted in a later layer still exist in the earlier one, so cleanup must happen in the same RUN instruction that creates the mess:

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

The --no-install-recommends flag skips suggested packages, and removing the apt lists in the same layer keeps them out of the final image entirely.

6. Run as a Non-Root User and Pin Versions

Containers run as root by default. If the application is compromised, the attacker starts with maximum privileges inside the container. Create a dedicated user, switch to it, and pin both base images and dependencies to exact versions so builds are reproducible:

FROM python:3.12.4-slim
RUN useradd --create-home appuser
WORKDIR /home/appuser/app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
USER appuser
CMD ["python", "app.py"]

Troubleshooting

Builds are still slow. Run docker build --progress=plain to see which layer takes the longest, and check whether your .dockerignore is actually excluding large folders.

Image is still large. Inspect layer sizes with docker history your-image. The biggest layer usually points straight at the instruction you need to fix.

App breaks on Alpine. You are probably hitting a musl vs glibc incompatibility. Switch the final stage to the slim (Debian) variant of the same image.

Conclusion

Good images are small, fast to build and boring to attack. Choose slim base images, order layers for caching, separate build from runtime with multi-stage builds, keep the context clean with .dockerignore, and never run as root. Once your images are lean, the next step is shipping them efficiently — see our tutorial on building a CI/CD pipeline with GitHub Actions. For the complete official reference, consult the Dockerfile best practices documentation.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.