|
1 | 1 | FROM python:3.11-slim
|
2 | 2 |
|
3 |
| -WORKDIR /app |
4 |
| -RUN pip install --no-cache-dir gunicorn |
5 |
| - |
6 |
| -COPY requirements.txt . |
7 |
| -RUN pip install --no-cache-dir -r requirements.txt |
| 3 | +# Set environment variables |
| 4 | +ENV PYTHONUNBUFFERED=1 \ |
| 5 | + PYTHONDONTWRITEBYTECODE=1 \ |
| 6 | + ENV_MODE="production" \ |
| 7 | + PYTHONPATH=/app |
8 | 8 |
|
| 9 | +WORKDIR /app |
9 | 10 |
|
10 |
| -# Copy the .env file first |
11 |
| -# COPY .env . # ATTENTION. We shouldn't copy secrets to the image |
| 11 | +# Install system dependencies |
| 12 | +RUN apt-get update && apt-get install -y --no-install-recommends \ |
| 13 | + build-essential \ |
| 14 | + curl \ |
| 15 | + && rm -rf /var/lib/apt/lists/* |
12 | 16 |
|
13 |
| -# Copy the backend code |
14 |
| -COPY . . |
| 17 | +# Create non-root user and set up directories |
| 18 | +RUN useradd -m -u 1000 appuser && \ |
| 19 | + mkdir -p /app/logs && \ |
| 20 | + chown -R appuser:appuser /app |
15 | 21 |
|
16 |
| -# Set environment variable |
17 |
| -ENV PYTHONPATH=/app |
| 22 | +# Install Python dependencies |
| 23 | +COPY --chown=appuser:appuser requirements.txt . |
| 24 | +RUN pip install --no-cache-dir -r requirements.txt gunicorn |
18 | 25 |
|
| 26 | +# Switch to non-root user |
| 27 | +USER appuser |
19 | 28 |
|
20 |
| -ENV ENV_MODE="production" |
| 29 | +# Copy application code |
| 30 | +COPY --chown=appuser:appuser . . |
21 | 31 |
|
22 | 32 | # Expose the port the app runs on
|
23 | 33 | EXPOSE 8000
|
24 | 34 |
|
25 |
| -# 24 workers |
26 |
| -CMD ["gunicorn", "api:app", "--workers", "24", "--worker-class", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000", "--timeout", "600", "--graceful-timeout", "300", "--keep-alive", "250", "--max-requests", "0", "--max-requests-jitter", "0", "--forwarded-allow-ips", "*", "--worker-connections", "5000", "--worker-tmp-dir", "/dev/shm", "--preload"] |
| 35 | +# Calculate optimal worker count based on 16 vCPUs |
| 36 | +# Using (2*CPU)+1 formula for CPU-bound applications |
| 37 | +ENV WORKERS=33 |
| 38 | +ENV THREADS=2 |
| 39 | +ENV WORKER_CONNECTIONS=2000 |
| 40 | + |
| 41 | +# Gunicorn configuration |
| 42 | +CMD ["sh", "-c", "gunicorn api:app \ |
| 43 | + --workers $WORKERS \ |
| 44 | + --worker-class uvicorn.workers.UvicornWorker \ |
| 45 | + --bind 0.0.0.0:8000 \ |
| 46 | + --timeout 600 \ |
| 47 | + --graceful-timeout 300 \ |
| 48 | + --keep-alive 250 \ |
| 49 | + --max-requests 2000 \ |
| 50 | + --max-requests-jitter 400 \ |
| 51 | + --forwarded-allow-ips '*' \ |
| 52 | + --worker-connections $WORKER_CONNECTIONS \ |
| 53 | + --worker-tmp-dir /dev/shm \ |
| 54 | + --preload \ |
| 55 | + --log-level info \ |
| 56 | + --access-logfile - \ |
| 57 | + --error-logfile - \ |
| 58 | + --capture-output \ |
| 59 | + --enable-stdio-inheritance \ |
| 60 | + --threads $THREADS"] |
0 commit comments