# Use lighter Python image optimized for production FROM python:3.10-slim LABEL maintainer="Yuwarath Suktrakool " # Set environment variables for optimization and configuration paths ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ PIP_NO_CACHE_DIR=1 \ PIP_DISABLE_PIP_VERSION_CHECK=1 \ OMP_NUM_THREADS=2 \ MKL_NUM_THREADS=2 \ TORCH_NUM_THREADS=2 \ MPLCONFIGDIR=/home/appuser/.config/matplotlib \ YOLO_CONFIG_DIR=/home/appuser/.config/Ultralytics # App configuration (can be overridden at runtime) ENV MAX_CONCURRENT=2 \ MAX_QUEUE_SIZE=10 \ REQUEST_TIMEOUT=60 \ CONFIDENCE_THRESHOLD=0.6 \ JPEG_QUALITY=85 # Create non-root user, /app directory, and config directories all at once RUN useradd -m appuser && \ mkdir -p /app /home/appuser/.config/matplotlib \ /home/appuser/.config/Ultralytics \ /home/appuser/.local && \ chown -R appuser:appuser /app /home/appuser # Set the working directory WORKDIR /app # Install system dependencies (as root) RUN apt-get update && \ apt-get install -y --no-install-recommends \ ffmpeg libsm6 libxext6 git curl \ && rm -rf /var/lib/apt/lists/* # Copy requirements first and set ownership to leverage Docker cache COPY --chown=appuser:appuser requirements.txt . # Install Python dependencies (as root) RUN pip install --no-cache-dir -r requirements.txt # --- Switch to appuser to create files --- # By running git clone as 'appuser', the files will already have the correct owner USER appuser # Clone YOLOv5 as appuser and remove .git to reduce size RUN git clone --depth 1 https://github.com/ultralytics/yolov5.git && \ rm -rf yolov5/.git # --- Switch back to root to copy remaining files --- # This is necessary because the build context files (from your computer) are owned by root USER root # Copy application code and set ownership # This REPLACES your old 'COPY . .' and the failing 'RUN chown...' COPY --chown=appuser:appuser . . # Switch to non-root user for runtime USER appuser # Expose port for Hugging Face Spaces EXPOSE 7860 # Health check - verify API is responding HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \ CMD curl -f http://localhost:7860/health || exit 1 # Run with 2 workers for better concurrency, with keep-alive for connection reuse CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "2", "--timeout-keep-alive", "30", "--limit-concurrency", "20"]