Deploy a Flask App to Lightsail or other VS

Sudo apt update 
Sudo apt upgrade 
sudo apt-get -y install python3-pip 

If apt can’t find the module add the repository:

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get -y install python3-pip 

Install pipenv

pip3 install pipenv

Clone your repository

git clone https://github.com/account/myproject.git
cd project

Install the environment

pipenv install

I had problems with this and had to uninstall the apt vetrsion of virtualenv

sudo apt remove python3-virtualenv

Look for the green line under Creating virtual environment

Virtualenv location: /home/azureuser/.local/share/virtualenvs/myproject-qDDIoa4O

Make a note of that location

Configure Gunicorn

pipenv shell
pip install gunicorn
gunicorn --bind 0.0.0.0:5000 'myproject:create_app()'

in Azure and AWS port 5000 is blocked but you can create an ssh tunnel to test to make sure your app is working:

#Local Terminal
ssh -N -L 5000:127.0.0.1:5000 <server ip>

in a browser go to http://127.0.0.1:5000/ and your app should pop up.

ctrl-c to terminate the gunicorn process

exit

to leave the virtual environment

vim  /etc/systemd/system/myproject.service 

[Unit]
Description=Gunicorn instance to serve myproject
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/myprojectdir
Environmment="PATH=/home/ubuntu/.local/share/virtualenvs/myproject-8Mk7vn
ExecStart=/home/ubuntu/.local/share/virtualenvs/myproject-8Mk7vntI/bin/gunicorn --workers 3 --bind unix:myproject.sock -m 007 myproject:create_app()

[Install]
WantedBy=multi-user.target

Start and enable service:

sudo systemctl start myproject
sudo systemctl enable myproject

Configure Nginx

If nginx isn’t installed

sudo apt install nginx
sudo vim /etc/nginx/sites-available/myproject

i to insert

server {
    listen 80;
    server_name your_domain www.your_domain;

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

esc then :wq to write and quit

Link your site in available to sites-enabled

sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

run test

sudo nginx -t

Restart nginx

sudo systemctl restart nginx

Test from your browser that it’s working

Add SSL

https://certbot.eff.org/instructions?ws=nginx&os=ubuntufocal

ensure snap is installed

sudo snap install core; sudo snap refresh core

use snap to install certbot

sudo snap install --classic certbot

link the certbot to bin

sudo ln -s /snap/bin/certbot /usr/bin/certbot

Run certbot

sudo certbot --nginx

follow instructions and you’re set.