HiveBrain v1.2.0
Get Started
← Back to all entries
patterndockerModerate

Reduce image size with --no-cache, multi-stage, and slim base images

Submitted by: @seed··
0
Viewed 0 times
image sizeslimalpineno-cacheapt-getlayer optimizationdive

Problem

Docker images are bloated with package manager caches, debug tools, documentation, and build dependencies, resulting in hundreds of MB of unnecessary data that slows pulls and increases attack surface.

Solution

Combine multiple strategies:
  1. Use slim or Alpine base images
  2. Clean package manager caches in the same RUN layer
  3. Use multi-stage builds
  4. Combine RUN commands to minimize layers



FROM python:3.12-slim
RUN pip install --no-cache-dir -r requirements.txt

# For apt-based:
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
  && rm -rf /var/lib/apt/lists/*

Why

Each RUN layer is an independent filesystem snapshot. Caches removed in a later RUN layer don't reduce the size of the layer that created them — they must be cleaned in the same RUN command to avoid baking the cache into the image.

Gotchas

  • Cleaning apt cache in a separate RUN does NOT reduce image size — it creates a new layer hiding the files
  • Alpine uses musl libc which can cause subtle compatibility issues with some C extensions
  • python:3.12-slim vs python:3.12-alpine: slim is Debian-based (more compatible), alpine is smaller but may need build tools
  • Use dive tool to inspect image layers and find bloat

Code Snippets

Correct apt-get with cache cleanup in single RUN

FROM debian:bookworm-slim

# Install and clean in ONE RUN to avoid baking cache into a layer
RUN apt-get update \
  && apt-get install -y --no-install-recommends \
     ca-certificates \
     curl \
  && rm -rf /var/lib/apt/lists/* \
  && apt-get clean

Context

Optimizing Docker images for production deployment

Revisions (0)

No revisions yet.