# Production-grade Dockerfile for TB-Guard-XAI # Multi-stage build for optimized image size # ========== Stage 1: Builder ========== FROM python:3.11-slim as builder # Install build dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ libsm6 \ libxext6 \ libxrender-dev \ libgl1 \ libglib2.0-0 \ && rm -rf /var/lib/apt/lists/* # Create virtual environment RUN python -m venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" # Copy requirements COPY requirements.txt . # Install Python dependencies RUN pip install --no-cache-dir --upgrade pip && \ pip install --no-cache-dir -r requirements.txt # ========== Stage 2: Runtime ========== FROM python:3.11-slim # Install runtime dependencies only RUN apt-get update && apt-get install -y --no-install-recommends \ libsm6 \ libxext6 \ libxrender-dev \ libgl1 \ libglib2.0-0 \ curl \ && rm -rf /var/lib/apt/lists/* # Create non-root user RUN useradd -m -u 1000 appuser # Set working directory WORKDIR /app # Copy virtual environment from builder COPY --from=builder --chown=appuser:appuser /opt/venv /opt/venv # Copy application code COPY --chown=appuser:appuser . /app # Ensure /app and all subdirectories are writable by appuser RUN chown -R appuser:appuser /app # Set environment variables ENV PATH="/opt/venv/bin:$PATH" \ PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 # Switch to non-root user USER appuser # Health check HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \ CMD curl -f http://localhost:7860/health || exit 1 # Run application CMD ["python", "-m", "uvicorn", "backend:app", "--host", "0.0.0.0", "--port", "7860"]