Saturday, August 2, 2014

Install Flask on Amazon EC2

There are are quite a few posts out there detailing how to install Flask on an Amazon instance - after trying out many methods, the following worked for me

I will be listing all the steps required to get a "Hello World" Python Flask application running on an Amazon EC instance

1. Create an Amazon account at http://aws.amazon.com/ec2/ - you can create micro-instances for free for a 1-year period - this is sufficient for testing purposes

2. After signing up, go to "Services -> EC2" and create new instance - follow the wizard - pick an Amazon AMI or Redhat/Centos AMI - this guide will refer to the yum utility to install flask et al.

3. Make sure you create a key-value pair - this is necessary for connecting via SSH later.

4. Download the .pem file to disk - I use Putty to run the console and WinSCP to upload files - Amazon has a straightforward tutorial on generating the appropriate private key format:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/putty.html

4. If you followed the steps correctly, you should be able to Putty to your instance now

5. Follow the guidelines here to install Flask, nginx and uwsgi:
https://github.com/d5/docs/wiki/Installing-Flask-on-Amazon-EC2

6. Add the following config option to your app.yaml file
   
      py-auto-reload: 1
This ensures uWSGI server does not need to be stopped and restarted every time you make a change in hello.py

7. Go to where it lists your EC2 instance and scroll to the right till you see the column called "Security Groups" - select your security group and in the new view, click "Actions -> Edit inbound rules"

Click "Add rule" and select "Type" as HTTP and leave the rest as-is - click save

8. Now go back to the EC2 view and locate the "Public DNS" column and copy the URL - the HTTP server is running on this URL on port 80 - open this in your browser eg.

http://ec2-20-21-22-23.eu-west-1.compute.amazonaws.com

You should see a "Hello World!" message

Alternatives:
- Create Elastic Beanstalk instance and launch Flask application from your PC shell using Amazon commandline tools: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_Python_flask.html
- PythonAnywhere: https://www.pythonanywhere.com/