Production DeploymentLesson 6.1
How to containerize a FastAPI app with Docker
Dockerfile, multi-stage builds, COPY requirements.txt, CMD uvicorn, .dockerignore, image layers, build cache, non-root user, production image size
Dockerizing a FastAPI App
A production-ready FastAPI Dockerfile should be minimal, use layer caching effectively, and run as a non-root user.
Dockerfile
FROM python:3.12-slim
WORKDIR /app
# Copy requirements first — cached if unchanged
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Create non-root user
RUN adduser --disabled-password --gecos '' appuser
USER appuser
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
.dockerignore
__pycache__
*.pyc
.env
.git
tests/
alembic/
*.md
Copying requirements.txt before the application code is the critical layer caching trick. Docker only re-runs pip install when requirements.txt changes — not on every code change.
Build and run
docker build -t my-api .
docker run -p 8000:8000 --env-file .env my-api
For multiple services, use Docker Compose to orchestrate the app, PostgreSQL, and Redis together. Never bake .env files into the image — mount them at runtime.
