docker.recipes

FastAPI + PostgreSQL

intermediate

Modern Python FastAPI with PostgreSQL and async support.

Overview

FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. Created by Sebastián Ramirez in 2018, FastAPI has rapidly gained adoption for its automatic API documentation generation, native async/await support, and exceptional performance that rivals Node.js and Go frameworks. It leverages Pydantic for data validation and Starlette for the web components, creating a developer-friendly framework that generates OpenAPI schemas automatically. This FastAPI and PostgreSQL combination creates a powerful foundation for data-driven web applications and APIs. PostgreSQL's advanced features like JSONB support, full-text search, and ACID compliance complement FastAPI's automatic validation and serialization capabilities. The asyncpg driver enables true asynchronous database operations, allowing the application to handle thousands of concurrent connections efficiently while PostgreSQL manages complex queries and maintains data integrity. This stack is ideal for startups building scalable APIs, enterprises migrating from Django REST or Flask applications, and developers creating modern web applications that require both high performance and robust data management. The automatic API documentation generation makes it particularly valuable for teams building microservices or public APIs, while PostgreSQL's reliability ensures production-grade data handling.

Key Features

  • Automatic OpenAPI/Swagger documentation generation with interactive API testing interface
  • Native async/await support with asyncpg for non-blocking PostgreSQL operations
  • Pydantic model integration for automatic request/response validation and serialization
  • FastAPI's dependency injection system for clean database session management
  • PostgreSQL JSONB support for hybrid relational-document data models
  • SQLModel compatibility for type-safe database operations with FastAPI
  • Hot reloading in development mode for rapid API iteration
  • PostgreSQL's advanced indexing and query optimization for high-performance data access

Common Use Cases

  • 1REST API backends for React, Vue, or Angular single-page applications
  • 2Microservices architectures requiring high-performance async communication
  • 3Data analytics platforms with complex PostgreSQL queries and JSON data processing
  • 4E-commerce platforms requiring ACID transactions and inventory management
  • 5IoT data collection systems handling high-frequency sensor data ingestion
  • 6Content management systems leveraging PostgreSQL's full-text search capabilities
  • 7Financial applications requiring PostgreSQL's transaction integrity and decimal precision

Prerequisites

  • Docker and Docker Compose installed with at least 4GB available memory
  • Python 3.7+ knowledge and familiarity with async/await programming concepts
  • Basic understanding of PostgreSQL and SQL query fundamentals
  • Port 8000 available for FastAPI application access
  • Knowledge of environment variable configuration and .env file management
  • Understanding of database migration concepts for Alembic usage

For development & testing. Review security settings, change default credentials, and test thoroughly before production use. See Terms

docker-compose.yml

docker-compose.yml
1services:
2 app:
3 build: .
4 container_name: fastapi
5 environment:
6 DATABASE_URL: postgresql+asyncpg://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
7 ports:
8 - "8000:8000"
9 depends_on:
10 - postgres
11 networks:
12 - fastapi
13
14 postgres:
15 image: postgres:16-alpine
16 container_name: postgres
17 environment:
18 POSTGRES_DB: ${DB_NAME}
19 POSTGRES_USER: ${DB_USER}
20 POSTGRES_PASSWORD: ${DB_PASSWORD}
21 volumes:
22 - postgres_data:/var/lib/postgresql/data
23 networks:
24 - fastapi
25
26volumes:
27 postgres_data:
28
29networks:
30 fastapi:
31 driver: bridge

.env Template

.env
1DB_NAME=fastapi
2DB_USER=fastapi
3DB_PASSWORD=changeme

Usage Notes

  1. 1Docs: https://fastapi.tiangolo.com/
  2. 2Create Dockerfile with Python + uvicorn
  3. 3Interactive API docs at http://localhost:8000/docs (Swagger)
  4. 4ReDoc at http://localhost:8000/redoc
  5. 5Async support with asyncpg, use SQLModel or SQLAlchemy 2.0
  6. 6Alembic for database migrations

Individual Services(2 services)

Copy individual services to mix and match with your existing compose files.

app
app:
  build: .
  container_name: fastapi
  environment:
    DATABASE_URL: postgresql+asyncpg://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
  ports:
    - "8000:8000"
  depends_on:
    - postgres
  networks:
    - fastapi
postgres
postgres:
  image: postgres:16-alpine
  container_name: postgres
  environment:
    POSTGRES_DB: ${DB_NAME}
    POSTGRES_USER: ${DB_USER}
    POSTGRES_PASSWORD: ${DB_PASSWORD}
  volumes:
    - postgres_data:/var/lib/postgresql/data
  networks:
    - fastapi

Quick Start

terminal
1# 1. Create the compose file
2cat > docker-compose.yml << 'EOF'
3services:
4 app:
5 build: .
6 container_name: fastapi
7 environment:
8 DATABASE_URL: postgresql+asyncpg://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
9 ports:
10 - "8000:8000"
11 depends_on:
12 - postgres
13 networks:
14 - fastapi
15
16 postgres:
17 image: postgres:16-alpine
18 container_name: postgres
19 environment:
20 POSTGRES_DB: ${DB_NAME}
21 POSTGRES_USER: ${DB_USER}
22 POSTGRES_PASSWORD: ${DB_PASSWORD}
23 volumes:
24 - postgres_data:/var/lib/postgresql/data
25 networks:
26 - fastapi
27
28volumes:
29 postgres_data:
30
31networks:
32 fastapi:
33 driver: bridge
34EOF
35
36# 2. Create the .env file
37cat > .env << 'EOF'
38DB_NAME=fastapi
39DB_USER=fastapi
40DB_PASSWORD=changeme
41EOF
42
43# 3. Start the services
44docker compose up -d
45
46# 4. View logs
47docker compose logs -f

One-Liner

Run this command to download and set up the recipe in one step:

terminal
1curl -fsSL https://docker.recipes/api/recipes/fastapi-postgres/run | bash

Troubleshooting

  • asyncpg.exceptions.InvalidCatalogNameError: Ensure POSTGRES_DB environment variable matches DATABASE_URL database name and postgres container has fully initialized
  • FastAPI startup fails with 'database connection refused': Add healthcheck to postgres service or implement retry logic in FastAPI database connection
  • uvicorn worker timeout errors under load: Increase worker_connections in uvicorn configuration and verify asyncpg connection pooling is properly configured
  • Pydantic validation errors on database model serialization: Ensure SQLModel or SQLAlchemy models inherit from BaseModel and use proper type annotations
  • PostgreSQL container fails to start with permission denied: Check that postgres_data volume has correct ownership or remove volume to reinitialize
  • FastAPI returns 500 errors on database queries: Enable SQLAlchemy echo=True to debug queries and verify async session management in dependency injection

Community Notes

Loading...
Loading notes...

Download Recipe Kit

Get all files in a ready-to-deploy package

Includes docker-compose.yml, .env template, README, and license

Ad Space