Python / FastAPI Basics Interview Questions
How do you containerise and deploy a FastAPI application with Docker?
Containerising FastAPI with Docker ensures consistent environments across development, staging, and production. Use a multi-stage build to keep the production image small, and run with Gunicorn + Uvicorn workers for production-grade concurrency.
# Dockerfile FROM python:3.12-slim AS base WORKDIR /app # Install dependencies first (layer caching) COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # Copy application code COPY . . # Create non-root user for security RUN adduser --disabled-password --gecos "" appuser USER appuser EXPOSE 8000 # Production: Gunicorn manages multiple Uvicorn worker processes CMD ["gunicorn", "main:app",\ "--workers", "4",\ "--worker-class", "uvicorn.workers.UvicornWorker",\ "--bind", "0.0.0.0:8000"]
# docker-compose.yml version: "3.9" services: api: build: . ports: - "8000:8000" environment: - DATABASE_URL=postgresql+asyncpg://user:pass@db/mydb - SECRET_KEY=${SECRET_KEY} # from .env depends_on: db: condition: service_healthy restart: unless-stopped db: image: postgres:16 environment: POSTGRES_USER: user POSTGRES_PASSWORD: pass POSTGRES_DB: mydb healthcheck: test: ["CMD-SHELL", "pg_isready -U user -d mydb"] interval: 5s retries: 5 volumes: - pgdata:/var/lib/postgresql/data volumes: pgdata:
| CPUs | Recommended workers (2*CPU+1) |
|---|---|
| 1 | 3 |
| 2 | 5 |
| 4 | 9 |
| 8 | 17 |
More Related questions...