Dylan Storey

Recovering academic, hacker, tinkerer, scientist.

Flask and AWS

Flask is awesome. AWS is awesome. Getting everything up and running isn’t always.

Getting a Flask app up and running on AWS

Before you start , I’m assuming you’re running an Ubuntu AWS instance specifically. A few things will need to change if you’re not but the general workflow should be the same

Assuming you have a project structure like so:

.
├── config.py
├── run.py
├── tmp/
└── project_name
    ├── config.py
    ├── data/
    ├── __init__.py
    ├── static
    │   ├── css/
    │   ├── fonts/
    │   └── js/
    ├── templates/
    └── views.py

Ensure run.py and project_name/init.py are good to go

run.py

#!/usr/bin/env python
from project_name import app

if __name__ == '__main__':
  app.run(debug = True)

project_name/__init__.py

from flask import Flask

app = Flask(__name__)


from project_name import views

Install dependencies

sudo apt-get install gunicorn python-flask nginx

Ensure your app will start with gunicorn

cd /home/ubuntu/project_name
gunicorn run:app 

This should start a server , if it fails for any reason fix it.

Create an upstart script for gunicorn to execute this app:

Create the file and open for editing:

sudo nano /etc/init/project_name.conf

Add this text in: edit project_name and the directory behind chdir :

description "Gunicorn application server running project_name"

start on runlevel [2345]
stop on runlevel [!2345]

respawn
setuid ubuntu
setgid www-data


chdir /home/ubuntu/project_name
exec gunicorn   --bind unix:project_name.sock -m 007 run:app

Close out and save.

Start your init script.

sudo start project_name

Configure NGINX

Go to your AWS console and get the public IP for your instance. Ensure that a .sock file exists at /home/ubuntu/project_name/project_name.sock

Open a new file edit server_domain_orIP to reflect your instance’s public IP.

sudo nano /etc/nginx/sites-available/project_name

This goes into that file:

server {
    listen 80;
    server_name server_domain_or_IP;

        location / {
        include proxy_params;
        proxy_pass http://unix:/home/ubuntu/project_name/project_name.sock;
    }
}

Activate your website and ensure everything looks ok:

sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
sudo nginx -t
sudo service nginx restart

You should be able to visit your public IP and see the site running now.

Troubleshooting

Nginx logs to : /var/log/nginx/error.log

blog comments powered by Disqus