Python Web App

Python web application deployment

Flask App Configuration

  1. Clone repository:

    sudo mkdir /etc/local/webs && \
    cd /etc/local/webs && \
    sudo git clone https://github.com/app.git && \
    sudo chown -R <user>:<user> app && \
    cd app
  2. Create python virtual environment & install dependencies:

    python -m venv .venv && \
    source .venv/bin/activate && \
    python -m pip install -r requirements.txt
  3. Configure WSGI - /usr/local/webs/app/app.wsgi:

    #!/usr/bin/python
    import sys
    import logging
    import os
    
    APP_DIR = "/usr/local/webs/app"
    os.environ["APP_DIR"] = APP_DIR
    
    logging.basicConfig(stream=sys.stderr)
    sys.path.insert(0, APP_DIR)
    
    from app import app as application
  4. Update owner:group

    cd /usr/local/web && \
    sudo chown -R www-data:www-data cmat

Apache Configuration

  1. Create custom Apache log directory:

    sudo mkdir /usr/local/webs/apache-logs && \
    sudo touch /usr/local/webs/apache-logs/app/error.log && \
    sudo touch /usr/local/webs/apache-logs/app/access.log && \
    sudo chown -R www-data:www-data /usr/local/webs/apache-logs
  2. Create configuration file:

    cd /etc/apache2/sites-available && \
    sudo vi app.conf
  3. Configuration - app.conf:

    <VirtualHost *:80>
        ServerName {DNS}
    
        ServerSignature Off
    
        RewriteEngine On
        RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
    
        ErrorLog /var/log/apache2/redirect.error.log
        LogLevel warn
    </VirtualHost>
    
    <VirtualHost *:443>
        ServerAdmin webmaster@localhost
        ServerName {DNS}
    
        DocumentRoot /usr/local/webs/app
    
        WSGIDaemonProcess web-app threads=5 python-home=/usr/local/webs/app/.venv
        WSGIProcessGroup web-app
        WSGIScriptAlias / /usr/local/webs/app/app.wsgi
        WSGIPassAuthorization On
        <Directory /usr/local/webs/app>
                Order allow,deny
                Allow from all
        </Directory>
    
        <Location />
                Require all granted
        </Location>
    
        ErrorLog /usr/local/webs/apache-logs/app/error.log
        CustomLog /usr/local/webs/apache-logs/app/access.log combined
    
        SSLEngine on
        SSLCertificateFile /etc/letsencrypt/live/{DNS}/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/{DNS}/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf
    </VirtualHost>
  4. Test configuration:

    sudo apache2ctl configtest
  5. Enable the site

    sudo a2ensite app.conf
  6. Restart Apache service

    sudo systemctl restart apache2