Skip to content

Refactor backend Dockerfile to implement multi-stage builds #10

@chigwell

Description

@chigwell

User Story
As a DevOps engineer,
I want to refactor the backend Dockerfile to use multi-stage builds
so that the production image excludes build tools and reduces both size and potential attack surface.

Background
The current backend/Dockerfile uses a single-stage build that includes Python runtime, build tools, and development dependencies in the final image. This results in:

  • Unnecessary bloat (~1.2GB image size due to python:3.8-slim with build tools).
  • Security risks from unused packages in production.
  • Slower deployment times due to larger image transfers.

The docker-compose.yml mounts the app directory as a volume, but the image still retains build artifacts and tools like pip cache. The frontend Dockerfile already uses a minimal runtime approach, but the backend implementation lags behind.

Acceptance Criteria

  • Modify backend/Dockerfile to implement two distinct stages:
    • Builder stage: Uses python:3.8-slim to install dependencies and copy application code.
    • Production stage: Uses a smaller base image (e.g., python:3.8-alpine) and copies only compiled artifacts from the builder.
  • Ensure the final image:
    • Excludes gcc, make, and other build tools.
    • Removes pip cache via --no-cache-dir and rm -rf /root/.cache/pip.
    • Retains functionality of the FastAPI endpoint at /.
  • Validation steps:
    • Run docker-compose build backend and confirm image size reduction using docker images.
    • Verify the API responds correctly via curl http://localhost:80/ after deployment.
    • Check absence of development packages in the final image using docker exec <container> sh -c "which gcc" (should return error).
  • Do not modify frontend/Dockerfile or React application code.
  • Update README.md build instructions if image tagging changes occur.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions