3 Hours

22. Dockerizing FastAPI Applications

Containerization

Docker containerization ensures your FastAPI application runs identically in development, testing, and production. This eliminates the classic it works on my machine problem. Docker packages your code, Python environment, dependencies, and configuration into a portable container. To test these examples, install Docker and run the commands below.

Dockerfile for FastAPI

A Dockerfile defines how to build your container image. Multi-stage builds keep production images small.

Text
FROM python:3.11-slim as builder

WORKDIR /app

RUN apt-get update && apt-get install -y --no-install-recommends gcc

COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt

FROM python:3.11-slim

WORKDIR /app

COPY --from=builder /root/.local /root/.local

COPY ./app /app/app
COPY ./alembic /app/alembic
COPY alembic.ini /app/

ENV PATH=/root/.local/bin:$PATH

RUN useradd -m -u 1000 fastapi && chown -R fastapi:fastapi /app
USER fastapi

EXPOSE 8000

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

Docker Compose for Development

Docker Compose orchestrates multiple containers (API, database, Redis) for local development.

Text
version: '3.8'

services:
  api:
    build: .
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgresql://fastapi:secret@db:5432/fastapi
      - REDIS_URL=redis://redis:6379
    depends_on:
      - db
      - redis
    volumes:
      - ./app:/app/app
    command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload

  db:
    image: postgres:15-alpine
    environment:
      - POSTGRES_USER=fastapi
      - POSTGRES_PASSWORD=secret
      - POSTGRES_DB=fastapi
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data

volumes:
  postgres_data:
  redis_data:

Production Docker Compose

Text
version: '3.8'

services:
  api:
    build: .
    restart: always
    environment:
      - DATABASE_URL=postgresql://fastapi:${DB_PASSWORD}@db:5432/fastapi
      - SECRET_KEY=${SECRET_KEY}
    depends_on:
      - db
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
    deploy:
      replicas: 3
      resources:
        limits:
          cpus: '0.5'
          memory: 512M

  db:
    image: postgres:15-alpine
    restart: always
    environment:
      - POSTGRES_USER=fastapi
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_DB=fastapi
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U fastapi"]
      interval: 10s

volumes:
  postgres_data:

.dockerignore File

Prevent unnecessary files from being copied into the Docker image.

Text
__pycache__
*.pyc
*.pyo
.python
.git
.gitignore
.env
.venv
venv
.DS_Store
.coverage
.pytest_cache
.mypy_cache
*.log
Dockerfile
docker-compose.yml
README.md

Building and Running

Bash
# Build the image
docker build -t fastapi-app .

# Run container
docker run -d -p 8000:8000 --name my-api fastapi-app

# View logs
docker logs -f my-api

# Stop and remove
docker stop my-api
docker rm my-api

# Docker Compose
docker-compose up -d
docker-compose down
docker-compose logs -f api
docker-compose exec api bash
Local Setup: Install Docker Desktop, then run docker-compose up -d to start all services. Your API will be available at http://localhost:8000.

Knowledge Check

Ready to test your understanding of 22. Dockerizing FastAPI Applications?

Back