# Flask + PostgreSQL

> Python Flask microframework with PostgreSQL and Celery.

- Category: Full Web Stacks
- Difficulty: intermediate
- Components: flask, postgres, redis
- Tags: flask, python, postgres, celery
- Source: https://docker.recipes/full-stacks/flask-postgres

## Overview

Flask is a lightweight Python microframework designed for building web applications and APIs with minimal boilerplate code. Created by Armin Ronacher in 2010, Flask follows the WSGI standard and embraces a 'micro' philosophy that provides core functionality while allowing developers to choose their preferred extensions and libraries. Its simplicity and flexibility have made it a popular choice for everything from simple web services to complex enterprise applications.

This stack combines Flask's lightweight web framework with PostgreSQL's enterprise-grade relational database and Redis-powered Celery for asynchronous task processing. PostgreSQL provides ACID-compliant data storage with advanced features like JSON support and full-text search, while Redis serves as both a message broker for Celery workers and a high-performance cache. The Celery integration allows Flask applications to offload time-consuming operations like email sending, image processing, or report generation to background workers.

This configuration is ideal for development teams building scalable web applications that need reliable data persistence, background job processing, and the flexibility to grow from prototype to production. Startups building SaaS platforms, development agencies creating client applications, and enterprises modernizing legacy systems will find this stack provides the right balance of simplicity and power without the complexity of larger frameworks like Django.

## Features

- Flask Blueprint architecture for modular application structure and reusable components
- PostgreSQL 16 with JSON/JSONB support for hybrid relational-document data models
- Celery worker processes for handling background tasks like email delivery and data processing
- Redis-based message brokering with sub-millisecond task queuing performance
- Flask-SQLAlchemy ORM integration with PostgreSQL for database operations and migrations
- Multi-container architecture separating web server, database, cache, and worker concerns
- Alpine Linux base images for minimal attack surface and faster container startup
- PostgreSQL connection pooling support for handling concurrent database requests

## Use cases

- SaaS applications requiring user authentication, billing, and background email processing
- E-commerce platforms with product catalogs, inventory tracking, and order processing workflows
- Content management systems with PostgreSQL's full-text search and JSON metadata storage
- Data analytics dashboards with Celery handling report generation and PostgreSQL aggregations
- API backends for mobile applications requiring real-time features and offline sync
- Internal business tools with form processing, file uploads, and automated notifications
- Prototype-to-production web applications that need to scale without framework migration

## Prerequisites

- Docker Desktop with 2GB+ available RAM for PostgreSQL and Redis operations
- Python development knowledge including decorators, context managers, and package management
- Basic SQL understanding for database schema design and query optimization
- Environment file (.env) with DB_NAME, DB_USER, and DB_PASSWORD variables configured
- Port 5000 available for Flask development server access
- Understanding of asynchronous task concepts for effective Celery worker utilization

## docker-compose.yml

```yaml
services:
  web:
    build: .
    container_name: flask
    environment:
      DATABASE_URL: postgres://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
      CELERY_BROKER_URL: redis://redis:6379/0
    ports:
      - "5000:5000"
    depends_on:
      - postgres
      - redis
    networks:
      - flask

  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:
      - flask

  redis:
    image: redis:alpine
    container_name: redis
    networks:
      - flask

  celery:
    build: .
    command: celery -A tasks worker --loglevel=info
    environment:
      DATABASE_URL: postgres://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}
      CELERY_BROKER_URL: redis://redis:6379/0
    depends_on:
      - redis
    networks:
      - flask

volumes:
  postgres_data:

networks:
  flask:
    driver: bridge
```

## .env

```bash
DB_NAME=flask
DB_USER=flask
DB_PASSWORD=changeme
```

## Usage notes

- Docs: https://flask.palletsprojects.com/
- Create Dockerfile with Python + gunicorn/uwsgi
- Access API at http://localhost:5000
- Celery worker handles async tasks (emails, processing)
- Flask-Migrate for database migrations: flask db upgrade
- Use Flask-SQLAlchemy for ORM

## Troubleshooting

- ImportError for Flask extensions: Install requirements.txt dependencies in Dockerfile and rebuild container
- Celery worker not processing tasks: Verify Redis connectivity and ensure task functions are properly decorated with @celery.task
- PostgreSQL connection refused: Check database container startup order and verify DATABASE_URL environment variable format
- Flask-Migrate version conflicts: Pin specific Flask-Migrate version in requirements.txt and ensure db folder is in COPY directive
- Redis memory usage warnings: Configure Redis maxmemory policy in redis.conf or add command parameters to docker-compose
- Static files not loading: Configure Flask static_folder path and ensure proper volume mounting for development

