| # --- Stage 1: Build Dependencies --- | |
| FROM python:3.9-slim as builder | |
| # Set environment variables to prevent writing .pyc files and for unbuffered output | |
| ENV PYTHONDONTWRITEBYTECODE 1 | |
| ENV PYTHONUNBUFFERED 1 | |
| # Set working directory | |
| WORKDIR /app | |
| # Install uvloop and gunicorn first as they are core dependencies | |
| RUN pip install --no-cache-dir uvloop gunicorn | |
| # Copy requirements and install the rest of the packages | |
| COPY requirements.txt . | |
| RUN pip install --no-cache-dir -r requirements.txt | |
| # --- Stage 2: Final Production Image --- | |
| FROM python:3.9-slim | |
| # Set the working directory | |
| WORKDIR /app | |
| # Set same environment variables for consistency | |
| ENV PYTHONDONTWRITEBYTECODE 1 | |
| ENV PYTHONUNBUFFERED 1 | |
| # Create a non-root user and group for security | |
| # This is a more robust way to create a user with a home directory | |
| RUN addgroup --system app && adduser --system --ingroup app --shell /bin/sh --home /app app | |
| # Copy installed packages AND binaries from the builder stage | |
| # This is the CRUCIAL FIX: copying /usr/local/bin where gunicorn lives | |
| COPY --from=builder /usr/local/lib/python3.9/site-packages /usr/local/lib/python3.9/site-packages | |
| COPY --from=builder /usr/local/bin /usr/local/bin | |
| # Copy the application code | |
| COPY . . | |
| # Change ownership of the app directory to the non-root user | |
| # This ensures the user can read the files | |
| RUN chown -R app:app /app | |
| # Switch to the non-root user | |
| USER app | |
| # Expose the port the app runs on | |
| EXPOSE 8000 | |
| # Run the application using Gunicorn | |
| # The command is now guaranteed to be in the PATH | |
| CMD ["gunicorn", "-c", "gunicorn_conf.py", "main:app"] |