# Use Python 3.11 slim as base image FROM python:3.11-slim AS builder # Set working directory WORKDIR /app # Install system dependencies required for OpenCV and other packages RUN apt-get update && apt-get install -y \ build-essential \ libgl1-mesa-glx \ libglib2.0-0 \ libsm6 \ libxext6 \ libxrender-dev \ cmake \ && rm -rf /var/lib/apt/lists/* # Create and activate virtual environment RUN python -m venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" # Install Python dependencies COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt # Disable numba caching by setting an environment variable RUN echo "NUMBA_CACHE_DIR=/tmp" >> /etc/environment # Final stage FROM python:3.11-slim # Copy virtual environment from builder COPY --from=builder /opt/venv /opt/venv # Set environment variables ENV PATH="/opt/venv/bin:$PATH" \ PYTHONUNBUFFERED=1 \ GRADIO_SERVER_NAME=0.0.0.0 \ GRADIO_SERVER_PORT=7860 \ NUMBA_CACHE_DIR=/tmp \ U2NET_HOME=/app/.u2net \ REMBG_CACHE_DIR=/app/.u2net # Install runtime system dependencies RUN apt-get update && apt-get install -y \ libgl1-mesa-glx \ libglib2.0-0 \ libsm6 \ libxext6 \ libxrender-dev \ && rm -rf /var/lib/apt/lists/* # Set working directory WORKDIR /app # Copy application code COPY . ./ # Create necessary directories with appropriate permissions RUN mkdir -p storage/uploads storage/processed && \ mkdir -p /app/.u2net && \ chmod 777 /app/.u2net storage/uploads storage/processed # Create a non-root user RUN useradd -m -u 1000 appuser && \ chown -R appuser:appuser /app # Switch to non-root user USER appuser # Ensure required Python imports are pre-compiled (optional for optimization) RUN python -m compileall . # Expose port EXPOSE 7860 # Set default command CMD ["python", "app.py"]