Deploying flask applications on AWS Ec2
Amazon Web Services are one of the best web services available in the market. And what web framework is better than Flask ?!
So, this time we are going to talk about deploying flask applications on AWS Ec2 for testing purposes.
The process is quiet simple.
Initially, make a new Ec2 instance on AWS.
now using SCP transfer your flask code to your ec2 instance, or type new one manually using
nano flask_app.py
let’s say we have a code as follows:
from flask import Flaskapp = Flask(__name__)@app.route("/")
def func():
return "hello world!"@app.route('/countme/<input_str>')
def count_me(input_str): return len(input_str)@app.route("/sayHi", methods=["POST"])
def get_page(): name = request.form['name']
return "hi"+str(name)if __name__ == "__main__": app.run(host="0.0.0.0", port=5000)
Here, the most important part was the host and port in the last line.
app.run(host="0.0.0.0", port=5000)
They will let you route to your flask application. For now, keep the host and port as mentioned above.
now go to the Ec2 dashboard and click on your instance, which will lead to the next page.
here, below instance summary, click on security tab
Here, click on the Security groups url. Once in it, go to inbound rules tab, and click on edit inbound rules
there add 2 new rules as mentioned below
and voila !! you’re all set to run and test your flask application.
Now go to your Ec2 instance shell and run your flask Application using
python flask_app.py
then, go to your instance page on AWS and click on your instance,
from there go to the networking tab and copy your public IPv4 address
and paste it in you browser, and add a :5000 behind it.
Now, it runs the same way as it did on your local host.
You need to keep one thing in mind though, this method is good only for testing, and not for deployment. You need to use a WSGI service, such as Gunicorn, uWSGI, cherryPi, etc. with apache or Nginx for deployment purposes.