Deploy Flask#
This page explains how to deploy a Flask project on Fly.io, the popular deployment platform for developers.
π New to App-Generator? SignIN with GitHub or Download a PRO Starter for only $19.99/mo
Framework Overview#
Flask is a lightweight WSGI web application framework written in Python. It implements a minimalistic core that can be extended with numerous official and community-created extensions. Flaskβs modular architecture makes it particularly suitable for microservices and API development, while maintaining the capability to scale into complex applications.
Deployment Configuration#
Project Structure#
A standard Flask application structure for deployment:
βββ app/
β βββ __init__.py
β βββ models.py
β βββ routes.py
β βββ templates/
βββ Dockerfile
βββ requirements.txt
βββ gunicorn.conf.py
βββ wsgi.py
Essential Files Configuration#
requirements.txt:
Flask==3.0.0
gunicorn==21.2.0
python-dotenv==1.0.0
Werkzeug==3.0.1
# Add other dependencies as needed
wsgi.py:
from app import create_app
app = create_app()
if __name__ == "__main__":
app.run()
gunicorn.conf.py:
# Gunicorn configuration
workers = 4
bind = "0.0.0.0:8080"
worker_class = "gthread"
threads = 2
timeout = 120
Dockerfile:
# Use Python 3.11 slim image
FROM python:3.11-slim
# Set working directory
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \
build-essential \
python3-dev \
&& rm -rf /var/lib/apt/lists/*
# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Set environment variables
ENV FLASK_APP=wsgi.py
ENV FLASK_ENV=production
ENV PYTHONUNBUFFERED=1
# Expose port
EXPOSE 8080
# Start Gunicorn
CMD ["gunicorn", "--config", "gunicorn.conf.py", "wsgi:app"]
.dockerignore:
__pycache__
*.pyc
*.pyo
*.pyd
.Python
env/
venv/
.env
*.log
.git/
.gitignore
Fly.io Configuration#
fly.toml:
app = "your-flask-app"
primary_region = "dfw"
[build]
dockerfile = "Dockerfile"
[env]
PORT = "8080"
[http_service]
internal_port = 8080
force_https = true
auto_stop_machines = true
auto_start_machines = true
min_machines_running = 1
processes = ["app"]
[[vm]]
cpu_kind = "shared"
cpus = 1
memory_mb = 256
Deployment Process#
Initialize Fly.io application:
fly launch
Configure environment variables:
fly secrets set FLASK_SECRET_KEY="your-secret-key"
fly secrets set DATABASE_URL="your-database-url"
Deploy the application:
fly deploy
Validate deployment:
fly status
Database Integration#
For PostgreSQL database integration:
Create a Fly PostgreSQL cluster:
fly postgres create
Attach database to your application:
fly postgres attach <database-name>
Update Flask configuration:
# config.py
import os
class Config:
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
SQLALCHEMY_TRACK_MODIFICATIONS = False
```
## SSL Configuration
SSL certificates are automatically managed by Fly.io. Configure your Flask application to handle HTTPS:
```python
# app/__init__.py
from flask_talisman import Talisman
def create_app():
app = Flask(__name__)
if not app.debug:
Talisman(app, force_https=True)
return app
Monitoring and Logging#
View application logs:
fly logs
Monitor application metrics:
fly status
fly monitor
Scaling Configuration#
Horizontal scaling:
fly scale count 2 # Scale to 2 instances
Vertical scaling:
fly scale vm shared-cpu-1x
Health Checks#
Implement a health check endpoint:
@app.route('/health')
def health_check():
return jsonify({"status": "healthy"}), 200
Update fly.toml to include health check:
[checks]
[checks.health]
port = 8080
type = "http"
interval = "15s"
timeout = "2s"
grace_period = "5s"
method = "GET"
path = "/health"
Performance Optimization#
Configure Gunicorn workers:
Update gunicorn.conf.py based on available resources:
import multiprocessing
workers = multiprocessing.cpu_count() * 2 + 1
threads = 2
worker_class = "gthread"
worker_connections = 1000
Implement caching:
from flask_caching import Cache
cache = Cache(config={'CACHE_TYPE': 'simple'})
@app.route('/cached-endpoint')
@cache.cached(timeout=300)
def cached_endpoint():
return expensive_operation()
Common Issues and Solutions#
Database Connection Issues - Verify DATABASE_URL in environment variables - Check database firewall rules - Validate connection pool settings
Memory Issues - Monitor memory usage with fly monitor - Adjust Gunicorn worker settings - Implement proper connection pooling
Static Files - Use WhiteNoise for static file serving - Configure proper caching headers - Consider using a CDN for large applications
This documentation provides a comprehensive guide for deploying Flask applications on Fly.io. Regular monitoring and maintenance of your deployed application is recommended for optimal performance.
Links#
π New to App-Generator? Join our 10k+ Community using GitHub One-Click SignIN.
π
Download
products and start fast a new projectπ Bootstrap your startUp, MVP or Legacy project with a custom development sprint