Flask Application Deployment
Deploying your Flask application to production requires careful consideration of performance, security, and scalability.
Production WSGI Server
# Install Gunicorn
pip install gunicorn
# Run with Gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 wsgi:app
Deployment to Heroku
# Create a Procfile
echo "web: gunicorn -w 4 -b 0.0.0.0:$PORT wsgi:app" > Procfile
# Create requirements.txt
pip freeze > requirements.txt
# Create runtime.txt (optional)
echo "python-3.9.7" > runtime.txt
# Deploy to Heroku
heroku login
heroku create
git push heroku main
heroku open
Deployment to AWS Elastic Beanstalk
# Install EB CLI
pip install awsebcli
# Initialize EB
eb init -p python-3.8 flask-app
eb create flask-env
eb open
Docker Deployment
# Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
EXPOSE 5000
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "wsgi:app"]
Nginx Configuration
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /static/ {
alias /path/to/your/static/files/;
expires 30d;
}
}
Environment Configuration
# config.py
import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-key'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
MAIL_SERVER = os.environ.get('MAIL_SERVER')
MAIL_PORT = int(os.environ.get('MAIL_PORT') or 25)
MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS') is not None
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
Deployment Checklist
- Use environment variables for sensitive configuration
- Disable debug mode in production
- Set a proper SECRET_KEY
- Use HTTPS with SSL certificates
- Implement proper logging
- Set up monitoring and alerts
- Configure automatic backups