# Production FastAPI Stack

> Production FastAPI with Nginx, Uvicorn, PostgreSQL, Redis, and Celery workers

- Category: Full Web Stacks
- Difficulty: advanced
- Components: nginx, fastapi, uvicorn, postgres, redis, celery
- Tags: fastapi, python, api, production, uvicorn, postgres, redis, celery
- Source: https://docker.recipes/full-stacks/production-fastapi-stack

## Overview

FastAPI is a modern, high-performance web framework for building APIs with Python, designed around Python type hints and automatic API documentation generation. This production stack combines FastAPI with Uvicorn's ASGI server for async request handling, Nginx as a reverse proxy for load balancing and static file serving, PostgreSQL for reliable ACID-compliant data storage, and Redis powering both caching and Celery's distributed task queue system. The architecture creates a robust, scalable API platform capable of handling both synchronous web requests and asynchronous background processing. This stack addresses the common production challenges of API development: horizontal scaling through Uvicorn workers, request buffering and SSL termination via Nginx, data persistence with PostgreSQL's advanced features like JSONB support, and background job processing through Celery workers with Redis as the message broker. The inclusion of Flower provides real-time monitoring of Celery tasks, while Celery Beat enables scheduled job execution. This configuration is ideal for SaaS platforms, data processing APIs, and enterprise applications that require both immediate API responses and background task execution. The combination of FastAPI's automatic OpenAPI documentation, PostgreSQL's query optimization capabilities, and Celery's distributed processing makes this stack particularly valuable for teams building complex data-driven applications that need to scale beyond simple CRUD operations.

## Features

- FastAPI's automatic OpenAPI and JSON Schema generation with interactive documentation at /docs endpoint
- Uvicorn ASGI server with configurable worker processes for handling concurrent async requests
- Nginx reverse proxy with event-driven architecture for high-throughput request handling and static file serving
- PostgreSQL JSONB support enabling hybrid relational-document data models within a single database
- Redis Pub/Sub messaging for real-time communication between API and Celery workers
- Celery distributed task queue with separate worker and beat scheduler containers for background processing
- Flower web-based monitoring dashboard for tracking Celery task execution, worker status, and queue metrics
- Database connection pooling through PostgreSQL with support for complex queries and transactions

## Use cases

- SaaS platforms requiring user authentication, subscription management, and background billing processes
- Data analytics APIs that need to process large datasets asynchronously while serving real-time query results
- E-commerce backends handling order processing, inventory updates, and automated email notifications
- Content management systems with media processing, thumbnail generation, and search indexing workflows
- IoT data collection platforms aggregating sensor data with scheduled reporting and alert systems
- Financial applications requiring transaction processing, compliance reporting, and automated reconciliation
- Multi-tenant applications needing isolated data processing and scheduled maintenance tasks per tenant

## Prerequisites

- Docker Engine 20.10+ and Docker Compose V2 for container orchestration support
- Minimum 2GB RAM (1GB for PostgreSQL, 512MB for Redis, 512MB for application containers)
- Available ports 80 (Nginx), 5555 (Flower), and configurable ports for external access
- Basic understanding of Python async/await patterns and FastAPI route decorators
- Familiarity with PostgreSQL connection strings and Redis URL formats for environment configuration
- Knowledge of Celery task definition syntax and worker scaling concepts

## docker-compose.yml

```yaml
services:
  nginx:
    image: nginx:alpine
    container_name: fastapi-nginx
    restart: unless-stopped
    ports:
      - "${NGINX_PORT:-80}:80"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - api

  api:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: fastapi-api
    restart: unless-stopped
    command: uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
    volumes:
      - ./app:/app
    environment:
      - DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
      - REDIS_URL=redis://redis:6379
      - SECRET_KEY=${SECRET_KEY}
      - ALGORITHM=HS256
    depends_on:
      - db
      - redis

  celery-worker:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: fastapi-celery-worker
    restart: unless-stopped
    command: celery -A worker worker -l info -c 4
    volumes:
      - ./app:/app
    environment:
      - DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
      - REDIS_URL=redis://redis:6379
    depends_on:
      - db
      - redis

  celery-beat:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: fastapi-celery-beat
    restart: unless-stopped
    command: celery -A worker beat -l info
    volumes:
      - ./app:/app
    environment:
      - DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
      - REDIS_URL=redis://redis:6379
    depends_on:
      - celery-worker

  flower:
    image: mher/flower:latest
    container_name: fastapi-flower
    restart: unless-stopped
    ports:
      - "${FLOWER_PORT:-5555}:5555"
    environment:
      - CELERY_BROKER_URL=redis://redis:6379
    depends_on:
      - redis
      - celery-worker

  db:
    image: postgres:16-alpine
    container_name: fastapi-db
    restart: unless-stopped
    environment:
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_DB=${DB_NAME}
    volumes:
      - postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    container_name: fastapi-redis
    restart: unless-stopped
    volumes:
      - redis_data:/data

volumes:
  postgres_data:
  redis_data:
```

## .env

```bash
# FastAPI Production Stack
NGINX_PORT=80
FLOWER_PORT=5555

# Security
SECRET_KEY=your-secret-key

# Database
DB_USER=fastapi
DB_PASSWORD=fastapi_password
DB_NAME=fastapi_db
```

## Usage notes

- FastAPI auto-generates OpenAPI docs at /docs
- Flower monitors Celery tasks at localhost:5555
- Uvicorn runs with multiple workers for concurrency
- Use Alembic for database migrations
- Redis serves as Celery broker and result backend
- Scale workers: docker compose up -d --scale celery-worker=4

## Troubleshooting

- uvicorn.error - Application startup failed: Verify DATABASE_URL format and ensure PostgreSQL container is running before API container starts
- celery.exceptions.NotRegistered - Task not found: Check that task functions are properly imported in worker.py and decorated with @celery.task
- redis.exceptions.ConnectionError: Ensure Redis container is accessible and REDIS_URL environment variable matches the service name 'redis:6379'
- nginx: [emerg] host not found in upstream: Verify API service name matches upstream configuration in nginx.conf and API container is running
- psycopg2.OperationalError - connection limit exceeded: Increase PostgreSQL max_connections or implement connection pooling in FastAPI database configuration
- Flower shows no workers: Confirm celery-worker container is running and CELERY_BROKER_URL in Flower matches Redis service endpoint

