How to reduce Docker image size?

· Category: Docker

Short answer

Reduce Docker image size by choosing minimal base images, using multi-stage builds, combining cleanup commands with RUN, and avoiding unnecessary files in the build context.

Steps

  1. Use alpine, slim, or distroless base images.
  2. Use multi-stage builds to separate build and runtime.
  3. Combine installation and cleanup in a single RUN layer.
  4. Use .dockerignore to exclude large or unnecessary files.

Example

FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt     && rm -rf /root/.cache
COPY . .
CMD ["python", "app.py"]

Tips

  • Use docker history and dive to inspect layer sizes.
  • Avoid installing recommended packages with apt-get install --no-install-recommends.
  • Pin versions and avoid apt-get upgrade in Dockerfiles.

Common issues

  • Leaving package manager caches in the image adds hundreds of megabytes.
  • COPY . . includes node_modules or .git if not ignored.
  • Using ubuntu:latest instead of alpine can increase size by an order of magnitude.