| # --- Stage 1: Build Dependencies --- | |
| FROM python:3.9-slim as builder | |
| # Set working directory | |
| WORKDIR /app | |
| # Install uvloop first as it's a build dependency for some packages | |
| RUN pip install --no-cache-dir uvloop | |
| # Copy requirements and install them | |
| 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 | |
| # Create a non-root user and group for security | |
| RUN addgroup --system app && adduser --system --group app | |
| # Copy installed packages from the builder stage | |
| COPY --from=builder /usr/local/lib/python3.9/site-packages /usr/local/lib/python3.9/site-packages | |
| # Copy the application code | |
| COPY . . | |
| # Change ownership of the app directory to the non-root user | |
| 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 | |
| CMD ["gunicorn", "-c", "gunicorn_conf.py", "main:app"] |