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.