Previously we have setup a very basic Flask application that runs locally. Next, we will deploy our Flask app on an AWS EC2 instance. This tutorial assumes that you have already setup an EC2 instance. If you haven’t done so, please refer to the official documentation.
Installations
SSH into your EC2 instance. Then, in the install Flask and gunicorn (a python web server gateway)
// if you don't have pip yet, run
$ python3 -m ensurepip --upgrade
// install flask and gunicorn
$ pip3 install flask gunicorn
Create the application
application.py
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!'
Start the application
gunicorn -b 0.0.0.0:8000 application:app
Configure instance port
Conclusion
Congratulations! You have successfully deployed a Flask application on an AWS EC2 instance. We used gunicorn, a Python WSGI HTTP server, to serve our Flask application.
Remember, while running the application on port 8000 is suitable for development or testing, a production-ready application should ideally be configured to run behind a reverse proxy like Nginx or Apache. This helps secure your app by reducing its exposure to the internet and also allows it to serve static files efficiently.