Reduce size of Docker image
Reducing the size of Docker images is crucial for optimizing resource usage, speeding up deployments, and minimizing storage requirements.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello():
return None
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
FROM python:3.9
WORKDIR /app
COPY . .
RUN pip install flask
CMD ["python","app.py"]
Here you can see the size of docker images is around 1 GB.
Here are several tips to help you reduce the size of your Docker images:
Use a Minimal Base Image
Start with a minimal base image, such as ->
slim
,slim-bullseye
, instead of a full-fledged operating system. These lightweight images contain only essential components.Multi-Stage Builds:
Use multi-stage builds to reduce the size of the final image. This involves using multiple
FROM
statements in your Dockerfile to create temporary images for building and then copying only necessary artifacts to the final image.
#stage-1
FROM python:3.9 AS stage-1
WORKDIR /app
COPY . .
#stage-2
FROM python:3.9-slim-bullseye # slim-bullseye is smaller base image
COPY --from=stage-1 /app /app
RUN pip install flask
CMD ["python","app.py"]
Now after use slim-bullseye base image, you can see that size reduce from 1GB to 135 MB