Quick Tip: Find Which Python Package Bloats Your Docker Image by 200MB (One Command)
Your Docker image is 800MB. Your code is 2MB. Here's how to find the culprit in 10 seconds.
The One-Liner
docker run --rm -it your-image pip list --format=freeze | sort -t= -k3 -n | tail -20
Or if you want sizes:
docker run --rm -it your-image sh -c "pip list | tail -n +3 | awk '{print \$1}' | xargs pip show | grep -E '^(Name|Location)' | paste - - | awk '{print \$2}' | xargs -I {} du -sh /usr/local/lib/python3.11/site-packages/{} 2>/dev/null | sort -rh | head -20"
The Better Way: dive
# Install once
go install github.com/wagoodman/dive@latest
# Analyze
dive your-image:latest
What you see:
- Every layer, every file, every byte
- Which
pip installadded 300MB ofnumpyyou don't use - That
apt-get installyou forgot to clean up
Real Example: My Image Before/After
| Package | Size | Used? | Action |
|---|---|---|---|
torch |
2.1GB | No (only needed transformers) |
Removed |
scipy |
180MB | No | Removed |
pandas |
95MB | Yes | Kept |
numpy |
45MB | Yes | Kept |
transformers |
25MB | Yes | Kept |
Result: 2.4GB → 180MB (93% smaller)
The Pip Trick for Local Dev
# Find what's actually imported
pip install pipreqs
pipreqs /path/to/your/project --force
# Compare with what you installed
pip freeze > installed.txt
diff requirements.txt installed.txt
Docker Layer Cleanup Pattern
# ❌ Bad: 3 layers, cache stays
RUN apt-get update
RUN apt-get install -y gcc
RUN pip install -r requirements.txt
# ✅ Good: 1 layer, cache cleaned
RUN apt-get update && \
apt-get install -y --no-install-recommends gcc && \
pip install --no-cache-dir -r requirements.txt && \
apt-get purge -y gcc && \
rm -rf /var/lib/apt/lists/*
Size difference: 340MB → 89MB for the same functionality
What's the biggest "why is this installed?" package you've found in a production image?
More Python tips: Free Dev Resources
Top comments (0)