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


1#!/usr/bin/env python
2from project_name import app
4if __name__ == '__main__':
5  app.run(debug = True)


1from flask import Flask
3app = Flask(__name__)
6from project_name import views

Install dependencies

1sudo 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:

1sudo 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]

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.

1sudo 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.

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

This goes into that file:

1server {
2    listen 80;
3    server_name server_domain_or_IP;
5        location / {
6        include proxy_params;
7        proxy_pass http://unix:/home/ubuntu/project_name/project_name.sock;
8    }

Activate your website and ensure everything looks ok:

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

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


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