Serving Flask Applications with uSWGI on Ubuntu

Introduction

Prerequisites

Step 1 — Setting Up Required Components and Tools

bash
sudo apt-get update
sudo apt-get install python-pip python-dev nginx
bash
sudo pip install virtualenv
bash
mkdir ~/samepleapp
cd ~/sampleapp
bash
user@instance:~/samepleapp $ virtualenv venv
bash
user@instance:~/samepleapp $ source venv/bin/activate

Step 2 — Creating a Sample Flask Application

bash
(venv) user@instance:~/samepleapp $ pip install flask uwsgi
bash
(venv) user@instance:~/samepleapp $ nano app.py
bash
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "It Works!"
if __name__ == "__main__":
app.run(host='0.0.0.0',port=3000)
reStructuredText
Note: Make sure your port 3000 is open over the Internet.
bash
(venv) user@instance:~/samepleapp $ python app.py

Step 3 — Configuring uWSGI

python
from app import app
if __name__ == "__main__":
app.run()
bash
(venv) user@instance:~/samepleapp $ uwsgi --socket 0.0.0.0:3000 --protocol=http -w wsgi:app
ini
[uwsgi]
#python module to import
module = wsgi:app
#enable the master process
master = true
#spawn number of workers
processes = 5
#socket file's location
socket = sampleflask.sock
#permissions for the socket file
chmod-socket = 660

Step 4 — Creating systemd unit file

ini
#Metadata and dependencies section
[Unit]
Description=Sampleflask service
After=network.target
#Define users and app working directory
[Service]
User=<your_user>
Group=www-data
WorkingDirectory=/home/<your_user>/sampleflask
Environment="PATH=/home/<your_user>/sampleflask/venv/bin"
ExecStart=/home/<your_user>/sampleflask/venv/bin/uwsgi --ini sampleflask.ini
#Link the service to start on multi-user system up
[Install]
WantedBy=multi-user.target
bash
(venv) user@instance:~/samepleapp $ sudo systemctl start sampleflask
(venv) user@instance:~/samepleapp $ sudo systemctl enable sampleflask

Step 5 — Configuring Nginx to Proxy requests

nginx
server {
# the port your site will be served on
listen 80;
# the IP Address your site will be served on
server_name <your_ip>;
# Proxy connections to application server
location / {
include uwsgi_params;
uwsgi_pass unix:/home/<your_user>/sampleflask/sampleflask.sock;
}
}
bash
(venv) user@instance:~/samepleapp $ sudo ln -s /etc/nginx/sites-available/sampleflask /etc/nginx/sites-enabled
bash
(venv) user@instance:~/samepleapp $ sudo ngnix -t
bash
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
bash
(venv) user@instance:~/samepleapp $ sudo systemctl restart nginx

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store