0
0
Dockerdevops~30 mins

Reducing final image size by 80 percent in Docker - Mini Project: Build & Apply

Choose your learning style9 modes available
Reducing final image size by 80 percent
📖 Scenario: You are working on a Docker project where the final image size is too large. Large images take longer to download and use more storage. Your goal is to reduce the final Docker image size by 80% using best practices.
🎯 Goal: Build a Dockerfile that creates a small final image by using a multi-stage build and a minimal base image.
📋 What You'll Learn
Create a Dockerfile with a multi-stage build
Use python:3.12-slim as the base image in the first stage
Use python:3.12-alpine as the base image in the final stage
Copy only necessary files from the build stage to the final stage
Install only required dependencies in the final image
Print the final image size after building
💡 Why This Matters
🌍 Real World
Reducing Docker image size helps in faster deployments, less storage use, and better performance in cloud environments.
💼 Career
DevOps engineers and developers often optimize Docker images to improve CI/CD pipelines and production deployments.
Progress0 / 4 steps
1
Create the initial Dockerfile with a base image
Create a Dockerfile starting with the base image python:3.12-slim using the FROM instruction.
Docker
Need a hint?

Use the FROM keyword followed by python:3.12-slim to specify the base image.

2
Add a build stage with dependencies installation
Add a build stage named builder using FROM python:3.12-slim AS builder. Then add a line to install pip packages flask and requests using RUN pip install flask requests.
Docker
Need a hint?

Use AS builder to name the stage. Use RUN pip install flask requests to install packages.

3
Create the final minimal image stage
Add a final stage starting with FROM python:3.12-alpine. Copy the installed packages from the builder stage using COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages. Also copy the /usr/local/bin folder from builder to the final image. Set the default command to python3.
Docker
Need a hint?

Use COPY --from=builder to copy files from the build stage. Use CMD ["python3"] to set the default command.

4
Build the image and print its size
Build the Docker image with tag small-python-app using docker build -t small-python-app .. Then run docker images small-python-app --format "{{.Size}}" to print the final image size.
Docker
Need a hint?

Use docker build -t small-python-app . to build. Use docker images small-python-app --format "{{.Size}}" to show size.