DEV Community

Cover image for Stop Shipping 1GB Docker Images: A Beginner’s Guide to Docker Optimization
Danang Adi Nugroho
Danang Adi Nugroho

Posted on Edited on

Stop Shipping 1GB Docker Images: A Beginner’s Guide to Docker Optimization

When you first start containerizing apps, getting your app to run inside Docker feels like a huge win. You write a Dockerfile, run docker build, and it works!

Then you check the image size: 1.2 GB for a simple API.

In a local environment, a 1GB image is a minor annoyance. In production, it becomes a real problem:

  • Slower CI/CD pipelines: Pushing and pulling massive images wastes minutes on every single deployment.
  • Slower autoscaling: When traffic spikes, spinning up new containers takes longer because the node has to pull a huge image first.
  • Higher cloud bills: Container registries and network egress charge for storage and bandwidth.
  • Larger attack surface: Bloated images ship with compilers, shells, and unused OS tools that attackers can exploit if your container is compromised.

The good news? You don't need advanced DevOps magic to fix this. Here are 8 practical, beginner-friendly tips to optimize your Docker images for size, speed, and security.


8 Ways to Optimize Your Docker Images

1. Always Use a .dockerignore File

Just like .gitignore, a .dockerignore file tells Docker which files and folders to exclude from the build context. Without it, Docker sends everything (including .git, node_modules, local .env files, and logs) to the Docker daemon. This slows down builds and risks leaking sensitive local files into your image.

Example .dockerignore:

.git
.env
node_modules
*.log
Dockerfile
Enter fullscreen mode Exit fullscreen mode

2. Optimize Your Dockerfile Instruction Order (Leverage Caching)

Docker builds images in layers and caches each step. If a layer changes, Docker invalidates the cache for that layer and every layer after it.

Put instructions that rarely change (like installing dependencies) at the top, and instructions that change frequently (like copying your source code) at the bottom.

# ✅ Good: Dependencies are cached unless package.json changes
COPY package*.json ./
RUN npm ci
COPY . .
Enter fullscreen mode Exit fullscreen mode

3. Combine Commands into a Single RUN Instruction

Every RUN command creates a new image layer. If you run apt-get update, apt-get install, and rm -rf /var/lib/apt/lists/* in separate RUN statements, the downloaded package cache still lives permanently in the earlier layer, bloating your image even after you "delete" it.

Chain them together with && so the cleanup happens in the same layer:

RUN apt-get update && \
    apt-get install -y --no-install-recommends curl && \
    rm -rf /var/lib/apt/lists/*
Enter fullscreen mode Exit fullscreen mode

4. Choose a Lightweight Base Image

Default base images (like node:22 or python:3.12) are built on full Debian installations packed with tools you'll never use in production. Switch to leaner alternatives:

  • slim: Strips out unnecessary packages while keeping standard GNU libraries (glibc). Great default for Node.js and Python.
  • alpine: Ultra-lightweight (~5MB) Linux distribution. Great for small footprints, though occasionally tricky with C-based dependencies.
  • distroless / scratch: Contains only your app and its runtime dependencies, with no shell and no package manager. Ideal for compiled languages like Go.

5. Use Multi-Stage Builds

This is the single biggest game-changer for reducing image size. With multi-stage builds, you use a heavy image with compilers and build tools in Stage 1 to build your app, then copy only the final compiled artifact into a tiny base image in Stage 2.

Your production image stays lean, and your build tools never ship to production.

6. Use Secret Mounts Instead of Baking Secrets into Layers

Never pass API keys, SSH keys, or private registry tokens using ENV or COPY during a build. Even if you delete the file later, it remains retrievable in the image layer history.

Instead, use BuildKit's --mount=type=secret so the secret is only available during that specific RUN command and never saved to the final image:

RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
Enter fullscreen mode Exit fullscreen mode

7. Run as a Non-Root User

By default, containers run as root. If an attacker finds a vulnerability in your app, running as root gives them much higher privileges inside the container (and potentially on the host if they break out).

Create a dedicated non-root user and switch to it with USER:

RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
Enter fullscreen mode Exit fullscreen mode

8. Use Exec-Form for CMD

There are two ways to write CMD:

  • Shell form: CMD node server.js (wraps your app in /bin/sh -c)
  • Exec form: CMD ["node", "server.js"] (runs your app directly as PID 1)

Always use exec form. When your orchestrator (like Kubernetes or Docker) stops a container, it sends a SIGTERM signal. With shell form, the shell swallows the signal and your app won't shut down gracefully, forcing Docker to wait 10 seconds before killing it. Exec form passes signals straight to your app for fast, clean shutdowns.


Real-World Examples: Optimized Dockerfiles

Let's put these principles together for two of the most popular stacks today: Go and Node.js.

1. Go Application (From ~800MB down to ~10MB)

Because Go compiles to a single static binary, we can build it in the official Go image and run it inside scratch (an empty image) or distroless.

# Stage 1: Build
FROM golang:1.23-alpine AS builder

WORKDIR /app

# Leverage caching by downloading dependencies first
COPY go.mod go.sum ./
RUN go mod download

# Copy source code and compile a static binary
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /app/server .

# Stage 2: Production
FROM gcr.io/distroless/static-debian12:nonroot

WORKDIR /app

# Copy only the compiled binary from the builder stage
COPY --from=builder /app/server /app/server

# Distroless :nonroot tag already runs as a non-root user
EXPOSE 8080

# Use exec-form for graceful shutdowns
CMD ["/app/server"]
Enter fullscreen mode Exit fullscreen mode

2. Node.js Application (From ~1GB down to ~150MB)

For Node.js (e.g., Express, NestJS, or TypeScript apps), we install and build in one stage, then copy only production dependencies and the built files into a lightweight alpine image.

# Stage 1: Build
FROM node:22-alpine AS builder

WORKDIR /app

# Copy dependency definitions first for better caching
COPY package*.json ./
RUN npm ci

# Copy source code and build (e.g., TypeScript compilation)
COPY . .
RUN npm run build

# Remove devDependencies
RUN npm prune --omit=dev

# Stage 2: Production
FROM node:22-alpine

WORKDIR /app

# Set environment to production
ENV NODE_ENV=production

# Copy only production node_modules and compiled output
COPY --from=builder --chown=node:node /app/node_modules ./node_modules
COPY --from=builder --chown=node:node /app/dist ./dist
COPY --from=builder --chown=node:node /app/package.json ./package.json

# Switch to the built-in non-root user provided by the Node image
USER node

EXPOSE 3000

# Use exec-form
CMD ["node", "dist/main.js"]
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

Optimizing Docker images isn't just about chasing the smallest possible megabyte count. It's about faster deployments, lower costs, and safer production environments.

If you're just getting started, focus on .dockerignore, multi-stage builds, and

Top comments (0)