Script Valley
FastAPI: Build Production Python APIs
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.

Up next

How to manage environment variables and secrets in FastAPI production

Sign in to track progress

How to containerize a FastAPI app with Docker โ€” Production Deployment โ€” FastAPI: Build Production Python APIs โ€” Script Valley โ€” Script Valley