Skip to main content

Deploy Flask

This guide will help you deploy a Flask application to Deployxa.

Overview

Flask is a lightweight Python web framework for building web applications and APIs. Deployxa provides optimized deployments for Flask with automatic configuration.

Features:

  • Automatic framework detection
  • Python 3.8+ support
  • PostgreSQL and MySQL support
  • Gunicorn WSGI server
  • Automatic HTTPS
  • Global CDN

Prerequisites

  • A Flask application
  • A GitHub repository with your code
  • A Deployxa account
  • PostgreSQL or MySQL database (optional)

Quick Start

1. Create Your Flask App

If you don't have a Flask app yet:

mkdir my-flask-app
cd my-flask-app
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install flask gunicorn psycopg2-binary

Create app.py:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
return 'Hello, Deployxa!'

if __name__ == '__main__':
app.run()

2. Create requirements.txt

pip freeze > requirements.txt

Ensure it includes:

Flask>=3.0.0
gunicorn>=21.2.0
psycopg2-binary>=2.9.9

3. Push to GitHub

git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourusername/my-flask-app.git
git push -u origin main

4. Deploy to Deployxa

  1. Go to Deployxa Dashboard
  2. Click "New Project"
  3. Select your GitHub repository
  4. Deployxa will automatically detect Flask
  5. Click "Deploy"

Your app will be live in under 60 seconds!

Configuration

Detected Settings

Deployxa automatically detects these settings:

SettingValue
FrameworkFlask
Build Commandpip install -r requirements.txt
Output DirectoryN/A
Start Commandgunicorn app:app --bind 0.0.0.0:8000
Port8000

Custom Configuration

If you need to customize settings:

  1. Go to ProjectSettingsBuild
  2. Modify settings as needed
  3. Save changes

Example Custom Settings:

{
"buildCommand": "pip install -r requirements.txt",
"startCommand": "gunicorn app:app --bind 0.0.0.0:8000 --workers 3"
}

Environment Variables

Adding Environment Variables

  1. Go to ProjectEnvironment
  2. Click "Add Variable"
  3. Enter key and value
  4. Click "Save"

Common Flask Environment Variables:

FLASK_ENV=production
SECRET_KEY=your-secret-key-here
DEBUG=False

# Database (optional)
DATABASE_URL=postgresql://user:pass@host:5432/dbname

# API Keys
API_KEY=your-api-key

Using Environment Variables

In your Flask app:

import os
from flask import Flask

app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
app.config['DEBUG'] = os.environ.get('DEBUG', 'False').lower() == 'true'

@app.route('/')
def home():
return 'Hello, Deployxa!'

Database Configuration

Using SQLite (Simple)

For simple applications:

import sqlite3
from flask import g

DATABASE = 'app.db'

def get_db():
if 'db' not in g:
g.db = sqlite3.connect(DATABASE)
g.db.row_factory = sqlite3.Row
return g.db

@app.teardown_appcontext
def close_db(exception):
db = g.pop('db', None)
if db is not None:
db.close()

For production applications:

import os
import psycopg2
from flask import g

def get_db():
if 'db' not in g:
g.db = psycopg2.connect(os.environ.get('DATABASE_URL'))
return g.db

@app.teardown_appcontext
def close_db(exception):
db = g.pop('db', None)
if db is not None:
db.close()

Using SQLAlchemy

For complex applications:

pip install flask-sqlalchemy
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)

Custom Domains

Adding a Custom Domain

  1. Go to ProjectDomains
  2. Click "Add Domain"
  3. Enter your domain (e.g., example.com)
  4. Configure DNS records
  5. Wait for verification

DNS Configuration

For Apex Domain (example.com):

Type: A
Name: @
Value: 76.76.21.21

For Subdomain (www.example.com):

Type: CNAME
Name: www
Value: cname.deployxa.com

Performance Optimization

Enable Gunicorn Workers

Configure Gunicorn workers based on CPU cores:

gunicorn app:app --bind 0.0.0.0:8000 --workers 3

Formula: (2 x CPU_CORES) + 1

Enable Caching

Use Flask-Caching:

pip install flask-caching
from flask_caching import Cache

app.config['CACHE_TYPE'] = 'simple'
cache = Cache(app)

@app.route('/')
@cache.cached(timeout=60)
def home():
return 'Hello, Deployxa!'

Database Connection Pooling

Use connection pooling for better performance:

from sqlalchemy import create_engine
from sqlalchemy.pool import QueuePool

engine = create_engine(
os.environ.get('DATABASE_URL'),
poolclass=QueuePool,
pool_size=10,
max_overflow=20,
pool_timeout=30
)

Monitoring

Viewing Logs

  1. Go to ProjectLogs
  2. Select log type:
    • Build Logs: Deployment process
    • Runtime Logs: Application output
    • Error Logs: Application errors

Flask Logging

Configure logging:

import logging
from flask import Flask

app = Flask(__name__)

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@app.route('/')
def home():
logger.info('Home page accessed')
return 'Hello, Deployxa!'

Monitoring Metrics

  1. Go to ProjectAnalytics
  2. View metrics:
    • Request count
    • Response times
    • Error rates
    • Bandwidth usage
    • CPU/RAM usage

Health Checks

Deployxa automatically monitors your application:

  • HTTP health checks every 30 seconds
  • Automatic restart on failure
  • Alerts on consecutive failures

Add a health check endpoint:

@app.route('/health')
def health():
return {'status': 'healthy'}, 200

Troubleshooting

500 Internal Server Error

Problem: Application returns 500 error

Solution:

  1. Check runtime logs for errors
  2. Verify environment variables
  3. Check database connection
  4. Ensure SECRET_KEY is set
  5. Check for missing dependencies

Database Connection Failed

Problem: psycopg2.OperationalError

Solution:

  1. Verify DATABASE_URL is correct
  2. Check database host and port
  3. Ensure database exists
  4. Check firewall rules
  5. Verify database user permissions

Module Not Found

Problem: ModuleNotFoundError: No module named 'flask'

Solution:

  1. Check requirements.txt includes Flask
  2. Verify build command installs dependencies
  3. Check build logs for installation errors
  4. Redeploy

Slow Response Times

Problem: Application responds slowly

Solution:

  1. Increase Gunicorn workers
  2. Enable caching
  3. Optimize database queries
  4. Use connection pooling
  5. Upgrade plan for more resources

Static Files Not Serving

Problem: Static files return 404

Solution:

  1. Ensure static folder exists
  2. Check Flask static configuration
  3. Verify file paths are correct
  4. Use Flask's send_from_directory

Best Practices

Project Structure

my-flask-app/
├── app.py
├── requirements.txt
├── .env.example
├── static/
│ ├── css/
│ └── js/
├── templates/
│ └── index.html
└── README.md

Environment Variables

  • Never commit .env file
  • Use .env.example as template
  • Rotate SECRET_KEY regularly
  • Use different values per environment

Security

  • Keep Flask updated
  • Use HTTPS only
  • Set DEBUG=False in production
  • Use strong SECRET_KEY
  • Validate all inputs
  • Use parameterized queries
  • Enable CSRF protection

Performance

  • Use Gunicorn with multiple workers
  • Enable caching
  • Optimize database queries
  • Use connection pooling
  • Enable compression
  • Use CDN for static assets

Database

  • Use connection pooling
  • Index frequently queried columns
  • Use transactions for complex operations
  • Backup database regularly
  • Use SQLAlchemy for complex queries

Advanced Configuration

Custom Gunicorn Configuration

Create gunicorn.conf.py:

bind = '0.0.0.0:8000'
workers = 3
worker_class = 'sync'
timeout = 120
keepalive = 5
max_requests = 1000
max_requests_jitter = 50
accesslog = '-'
errorlog = '-'
loglevel = 'info'

Update start command:

gunicorn app:app -c gunicorn.conf.py

Blueprints for Large Apps

Organize large applications with Blueprints:

from flask import Flask, Blueprint

app = Flask(__name__)

# Create blueprints
auth_bp = Blueprint('auth', __name__, url_prefix='/auth')
api_bp = Blueprint('api', __name__, url_prefix='/api')

# Register blueprints
app.register_blueprint(auth_bp)
app.register_blueprint(api_bp)

Flask RESTful API

For REST APIs:

pip install flask-restful
from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

Error Handling

Implement custom error handlers:

from flask import jsonify

@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Not found'}), 404

@app.errorhandler(500)
def internal_error(error):
return jsonify({'error': 'Internal server error'}), 500

Examples

Basic Flask App

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
return 'Hello, Deployxa!'

@app.route('/about')
def about():
return 'About page'

if __name__ == '__main__':
app.run()

With Database

from flask import Flask, jsonify
import os
import psycopg2

app = Flask(__name__)

def get_db():
return psycopg2.connect(os.environ.get('DATABASE_URL'))

@app.route('/users')
def users():
db = get_db()
cur = db.cursor()
cur.execute('SELECT * FROM users')
users = cur.fetchall()
return jsonify(users)

REST API

from flask import Flask, request, jsonify

app = Flask(__name__)

items = []

@app.route('/api/items', methods=['GET'])
def get_items():
return jsonify(items)

@app.route('/api/items', methods=['POST'])
def create_item():
item = request.json
items.append(item)
return jsonify(item), 201

With Templates

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
return render_template('index.html', title='Home')

Resources


Need Help? Contact support@deployxa.com or join our community Discord.