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
- Use
alpine,slim, ordistrolessbase images. - Use multi-stage builds to separate build and runtime.
- Combine installation and cleanup in a single
RUNlayer. - Use
.dockerignoreto 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 historyanddiveto inspect layer sizes. - Avoid installing recommended packages with
apt-get install --no-install-recommends. - Pin versions and avoid
apt-get upgradein Dockerfiles.
Common issues
- Leaving package manager caches in the image adds hundreds of megabytes.
COPY . .includesnode_modulesor.gitif not ignored.- Using
ubuntu:latestinstead ofalpinecan increase size by an order of magnitude.