This project demonstrates an optimized approach to building Docker images for Python applications using Poetry. The goal is to reduce build times and image size while maintaining reproducibility and efficiency.
- Ensures deterministic builds by avoiding unexpected changes due to Poetry updates.
- Installed Poetry with a fixed version using:
RUN pip install poetry==<version>
- Avoids copying unnecessary files like
.venv, ensuring efficient layer caching. - Only essential files (
pyproject.toml,poetry.lock, and application source) are copied:COPY pyproject.toml poetry.lock ./ COPY <important parts of application>
- Reduces image size by installing only production dependencies with:
RUN poetry install --without dev
- Prevents cache bloat by removing Poetry's cache after dependency installation:
RUN poetry install --without dev && rm -rf $POETRY_CACHE_DIR
- Installs dependencies before copying the application code to avoid reinstalling dependencies on code changes:
RUN poetry install --without dev --no-root COPY <application> RUN poetry install --without dev
- Uses a
builderstage for installation and aruntimestage to keep the final image minimal:FROM python:3.11-buster as builder ... FROM python:3.11-slim-buster as runtime COPY --from=builder ${VIRTUAL_ENV} ${VIRTUAL_ENV}
- Results in a much smaller final image (~170MB vs. >1GB).
- Enables caching for dependency installations, speeding up repeated builds:
RUN --mount=type=cache,target=$POETRY_CACHE_DIR poetry install --without dev --no-root
- 🚀 Faster builds: Avoids redundant installations by leveraging Docker layer caching.
- 📉 Smaller image size: Reduces unnecessary files and dependencies.
- 🔄 Reproducibility: Ensures consistency by pinning Poetry versions and dependencies.
To build and run the Docker container:
DOCKER_BUILDKIT=1 docker build -t optimized-python-app .
docker run --rm optimized-python-appBy implementing these optimizations, the project achieves efficient, fast, and lightweight Docker builds while maintaining flexibility and ease of development.