Skip to content

Instantly share code, notes, and snippets.

@swyngaard
Last active August 30, 2018 00:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save swyngaard/296392c427504ce6f7ea81abb87aaee8 to your computer and use it in GitHub Desktop.
Save swyngaard/296392c427504ce6f7ea81abb87aaee8 to your computer and use it in GitHub Desktop.
Install Flask on Ubuntu 16.04

Install Flask on Ubuntu 16.04

sudo aptitude install --with-recommends python3-pip python3-dev nginx uwsgi uwsgi-plugin-python3 virtualenv
mkdir sensor-logger
cd sensor-logger
virtualenv --python=python3 .venv
source .venv/bin/activate
pip install -r requirements.txt
#start the application
python server.py
#visit the app using a web browser at http://localhost:5000
#stop the Flask server
Ctrl+C
#use uWSGI to serve the application instead
uwsgi --plugin python3 --venv $HOME/sensor-logger/.venv --socket 0.0.0.0:5000 --protocol=http -w wsgi:app
#visit the app using a web browser at http://localhost:5000
#stop uWSGI server
Ctrl+C
#create a uWSGI configuration file
echo -e '[uwsgi]
plugin = python3
venv = .venv

module = wsgi:app

master = true
processes = 1

socket = sensor-logger.sock
chmod-socket = 660
vacuum = true

die-on-term = true
enable-threads = true
threads = 3' | tee uwsgi.ini

#create a systemd service configuration file for uWSGI
echo "[Unit]
Description=uWSGI instance to serve myproject
After=network.target

[Service]
User=$USER
Group=www-data
WorkingDirectory=$HOME/sensor-logger
Environment=\"PATH=$HOME/sensor-logger/.venv/bin\"
ExecStart=/usr/bin/uwsgi --ini uwsgi.ini

[Install]
WantedBy=multi-user.target" | sudo tee /etc/systemd/system/sensor-logger.service

#start the uWSGI service
sudo systemctl start sensor-logger.service
sudo systemctl enable sensor-logger.service
#create a nginx configuration file
echo "server {
    listen 80;
    listen [::]:80 default_server;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:$HOME/sensor-logger/sensor-logger.sock;
    }
}" | sudo tee /etc/nginx/sites-available/default

#restart nginx
sudo systemctl restart nginx
#examine application logs using the following command
sudo journalctl -u sensor-logger

# Sources
# [1] https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-16-04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment