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
- Go to Deployxa Dashboard
- Click "New Project"
- Select your GitHub repository
- Deployxa will automatically detect Flask
- Click "Deploy"
Your app will be live in under 60 seconds!
Configuration
Detected Settings
Deployxa automatically detects these settings:
| Setting | Value |
|---|---|
| Framework | Flask |
| Build Command | pip install -r requirements.txt |
| Output Directory | N/A |
| Start Command | gunicorn app:app --bind 0.0.0.0:8000 |
| Port | 8000 |
Custom Configuration
If you need to customize settings:
- Go to Project → Settings → Build
- Modify settings as needed
- 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
- Go to Project → Environment
- Click "Add Variable"
- Enter key and value
- 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()
Using PostgreSQL (Recommended)
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
- Go to Project → Domains
- Click "Add Domain"
- Enter your domain (e.g.,
example.com) - Configure DNS records
- 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
- Go to Project → Logs
- 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
- Go to Project → Analytics
- 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:
- Check runtime logs for errors
- Verify environment variables
- Check database connection
- Ensure SECRET_KEY is set
- Check for missing dependencies
Database Connection Failed
Problem: psycopg2.OperationalError
Solution:
- Verify DATABASE_URL is correct
- Check database host and port
- Ensure database exists
- Check firewall rules
- Verify database user permissions
Module Not Found
Problem: ModuleNotFoundError: No module named 'flask'
Solution:
- Check requirements.txt includes Flask
- Verify build command installs dependencies
- Check build logs for installation errors
- Redeploy
Slow Response Times
Problem: Application responds slowly
Solution:
- Increase Gunicorn workers
- Enable caching
- Optimize database queries
- Use connection pooling
- Upgrade plan for more resources
Static Files Not Serving
Problem: Static files return 404
Solution:
- Ensure static folder exists
- Check Flask static configuration
- Verify file paths are correct
- 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
.envfile - Use
.env.exampleas 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')
Related Topics
Resources
Need Help? Contact support@deployxa.com or join our community Discord.