Reduce size

2 snippets in Docker

DKDocker

Use Small Base Images

DK · Best Practices
Syntax
FROM <image>:<version>-alpine
FROM <image>:<version>-slim
Example
# Instead of:
FROM node:20          # ~1GB
# Use:
FROM node:20-alpine   # ~130MB
FROM python:3.12-slim # ~150MB vs 900MB for full

Note Alpine images use musl libc instead of glibc, which can cause issues with some native Node.js modules or Python C extensions. Test thoroughly. Debian slim is a safer middle ground if Alpine causes problems.

Bloated Image Size

DK · Common Mistakes
Syntax
# Problem:
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y python3 build-essential ...
COPY . .
# 1.5GB image for a simple Python app
Example
# Fix:
FROM python:3.12-slim AS build
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

FROM python:3.12-slim
COPY --from=build /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
COPY . /app
CMD ["python", "/app/main.py"]

Note Common culprits: using the full Ubuntu/Debian base, leaving build tools installed, not cleaning apt/pip caches, copying node_modules into the image. Use docker history to identify the largest layers.

Frequently asked questions

How do you reduce size?
Docker covers this with 2 copy-ready snippets on this page. The "Use Small Base Images" snippet in Docker uses `FROM <image>:<version>-alpine`.
Which command does the Docker example use?
The "Use Small Base Images" snippet uses `FROM <image>:<version>-alpine`, from the Best Practices section of the Docker cheat sheet.
What other Docker snippets are shown for "reduce size"?
Besides "Use Small Base Images", this page also shows "Bloated Image Size".
Is there anything to watch out for?
Yes. For "Use Small Base Images": Alpine images use musl libc instead of glibc, which can cause issues with some native Node.js modules or Python C extensions. Test thoroughly. Debian slim is a safer middle ground if Alpine causes problems.