How to Deploy Flask Application: Step-by-Step Guide
To deploy a
Flask application, use a production server like Gunicorn to run your app and a web server like Nginx as a reverse proxy. This setup improves performance and security compared to the built-in Flask server.Syntax
Deploying a Flask app typically involves running your app with a WSGI server and optionally configuring a reverse proxy. The basic command to run your Flask app with Gunicorn is:
gunicorn [OPTIONS] MODULE_NAME:APP_VARIABLE
Where:
MODULE_NAMEis your Python file without.pyAPP_VARIABLEis the Flask app instance name (usuallyapp)OPTIONScan include number of workers, binding address, etc.
Example:
gunicorn --workers 3 --bind 0.0.0.0:8000 app:app
This runs your Flask app with 3 worker processes, listening on all IPs at port 8000.
bash
gunicorn --workers 3 --bind 0.0.0.0:8000 app:app
Example
This example shows a simple Flask app deployed with Gunicorn. It listens on port 8000 and serves a basic web page.
python
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Hello, Flask deployment!' if __name__ == '__main__': app.run(host='0.0.0.0', port=8000)
Output
Hello, Flask deployment!
Common Pitfalls
Common mistakes when deploying Flask apps include:
- Using the built-in Flask server (
app.run()) in production, which is not designed for performance or security. - Not setting the
FLASK_ENVorFLASK_DEBUGenvironment variables properly, leading to debug mode running in production. - Failing to configure a reverse proxy like Nginx, which helps handle client requests and improves security.
- Not using multiple worker processes, which limits app scalability.
Wrong way (using Flask's built-in server in production):
python app.py
Right way (using Gunicorn):
gunicorn --workers 3 --bind 0.0.0.0:8000 app:app
bash
python app.py # vs gunicorn --workers 3 --bind 0.0.0.0:8000 app:app
Quick Reference
Summary tips for deploying Flask apps:
- Use
Gunicornor another WSGI server for production. - Configure a reverse proxy like
Nginxfor better performance and security. - Run multiple worker processes to handle concurrent requests.
- Set environment variables to disable debug mode in production.
- Use HTTPS in production for secure communication.
Key Takeaways
Never use Flask's built-in server for production; use Gunicorn or similar WSGI servers.
Configure a reverse proxy like Nginx to improve security and performance.
Run multiple worker processes to handle more users efficiently.
Always disable debug mode in production by setting environment variables.
Use HTTPS and proper server configuration for secure deployment.