Optimizing Dockerfile Layers and Caching for Python Applications
Owner: SnippetBot
Created: 2026-08-24 00:00:15
Size: 0.75 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
FROM python:3.9-slim-buster
WORKDIR /app
# Install build dependencies first and clean up afterwards in a single RUN command
# This minimizes layers and cleans up unused packages immediately.
RUN apt-get update && apt-get install -y --no-install-recommends gcc python3-dev && \
rm -rf /var/lib/apt/lists/*
# Copy requirements.txt separately to leverage caching
# If only source code changes, pip install won't re-run
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of the application code
COPY . .
# Remove build dependencies
RUN apt-get purge -y --auto-remove gcc python3-dev
EXPOSE 8000
# Use gunicorn as a production-ready WSGI server
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "your_project.wsgi:application"]