# BookWyrm Base Multi-stage Build # Production-optimized build targeting ~400MB final image size # Shared base image for BookWyrm web and worker containers # Build stage - Install dependencies and prepare optimized source FROM python:3.11-slim AS builder # Install build dependencies in a single layer RUN apt-get update && apt-get install -y --no-install-recommends \ git \ build-essential \ libpq-dev \ libffi-dev \ libssl-dev \ && rm -rf /var/lib/apt/lists/* \ && apt-get clean WORKDIR /app # Clone source with minimal depth and remove git afterwards to save space RUN git clone -b production --depth 1 --single-branch \ https://github.com/bookwyrm-social/bookwyrm.git . \ && rm -rf .git # Create virtual environment and install Python dependencies RUN python3 -m venv /opt/venv \ && /opt/venv/bin/pip install --no-cache-dir --upgrade pip setuptools wheel \ && /opt/venv/bin/pip install --no-cache-dir -r requirements.txt \ && find /opt/venv -name "*.pyc" -delete \ && find /opt/venv -name "__pycache__" -type d -exec rm -rf {} + \ && find /opt/venv -name "*.pyo" -delete # Remove unnecessary files from source to reduce image size # Note: .dockerignore will exclude __pycache__, *.pyc, etc. automatically RUN rm -rf \ /app/.github \ /app/docker \ /app/nginx \ /app/locale \ /app/bw-dev \ /app/bookwyrm/tests \ /app/bookwyrm/test* \ /app/*.md \ /app/LICENSE \ /app/.gitignore \ /app/requirements.txt # Runtime stage - Minimal runtime environment FROM python:3.11-slim AS runtime # Set environment variables ENV TZ=UTC \ PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ PATH="/opt/venv/bin:$PATH" \ VIRTUAL_ENV="/opt/venv" # Install only essential runtime dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ libpq5 \ curl \ gettext \ && rm -rf /var/lib/apt/lists/* \ && apt-get clean \ && apt-get autoremove -y # Create bookwyrm user for security RUN useradd --create-home --shell /bin/bash --uid 1000 bookwyrm # Copy virtual environment and optimized source COPY --from=builder /opt/venv /opt/venv COPY --from=builder /app /app # Set working directory and permissions WORKDIR /app RUN chown -R bookwyrm:bookwyrm /app \ && mkdir -p /app/mediafiles /app/static /app/images \ && chown -R bookwyrm:bookwyrm /app/mediafiles /app/static /app/images # Default user USER bookwyrm # Health check HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \ CMD python manage.py check --deploy || exit 1