Jack Atkinson

Scientist, Archer, Coder

Deploying a flask app to a DO server under apache

2 minutes
January 2, 2023
computing,  website,  server, 


Prior: * Set up routing for site if multiple on server. * install wsgi for apache with apt install libapache2-mod-wsgi-py3

  1. Create flask app as per the guidelines on the flask website.
  2. Store on github
  3. Create /var/www/mysite/
  4. Clone from github into here
  5. Create virtual environment in /var/www/mysite/venv/ and activate. upgrade pip
  6. cd into the git repo /var/www/mysite/mysiterepo/ and install to venv with python3 -m pip install .
  7. Create new virtualhosts file at /etc/apache/sites-available/mysite.com.conf with contents:
<VirtualHost *:80>
    RewriteEngine On
    RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
    RewriteCond %{SERVER_NAME} =www.mysite.com [OR]
    RewriteCond %{SERVER_NAME} =mysite.com
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

<VirtualHost *:443>
    SSLEngine on
    # enable HTTP/2, if available
    Protocols    h2 http/1.1

    # HTTP Strict Transport Security (mod_headers is required) (63072000 seconds)
    Header always set Strict-Transport-Security "max-age=60;"

    CustomLog /var/log/apache2/access.log combined
    ErrorLog /var/log/apache2/error.log

    ServerName mysite.com
    ServerAlias www.mysite.com
    WSGIScriptAlias / /var/www/mysite.com/myapp.wsgi
    <Directory /var/www/mysite.com/mysiterepo/myapp/>
            Require all granted

    SSLCertificateFile /etc/letsencrypt/live/mysite.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/mysite.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf

# modern configuration, tweak to your needs
SSLProtocol             all -SSLv3 -TLSv1 -TLSv1.1
SSLHonorCipherOrder     off
SSLSessionTickets       off

SSLUseStapling On
SSLStaplingCache "shmcb:logs/ssl_stapling(32768)"
  1. Activate site with a2ensite mysite.com
  2. Reload apache with systemctl reload apache2
  3. Create /var/www/mysite.com/myapp.wsgi
import sys
import logging

from flaskr import create_app
application = create_app()
application.secret_key = 'mySecretKey'

This directs it to the venv installation

  1. Prepare the site by running flask --app flaskr init-db from within the venv.
  2. Go to the site

To update: * git pull into the repo * activate the venv and install again Unless there have been major changes to code or database then should be good to go