Apache https reverse proxy Uvicorn

Uvicorn is a Python web server and development server that supports a variety of frameworks such as Flask, Django, and FastAPI. Uvicorn is popular among developers for its high performance and ease of use.

I. Installation of Uvicorn

Installing venv for local python

# apt install python-venv

To facilitate isolation from root, create a new general user mysiteuser

# useradd -m mysiteuser
# passwd mysite

Login to ssh with mysiteuser

ssh mysiteuser@123.123.123.123

Creating a python virtual environment

$ python -m venv . /venv

Installing uvicorn in a virtual environment

$./venv/bin/pip install uvicorn

uvicorn configuration, here's an example mymodule.py for running a flask program

#!/bin/python

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello(): return 'Hello, World!
        return 'Hello, World!

if __name__ == '__main__': uvicorn.run(app,host='0.0.0',port=3.0.0')
        uvicorn.run(app,host='0.0.0.0',port=3000)

Use the following command to start the server:

. /venv/bin/uvicorn mymodule:app --reload

where mymodule is the name of the Python module that contains the Flask application

II. Installation of Apache

The Apache configuration file is located in /etc/apache2/sites-available/.

Create the file mysite.conf

Save the configuration and enable it

a2ensite mysite.conf

Restart Apache to apply the changes

systemctl restart apache2

III. Integration

Install apache2 support for wsgi.

apt-get install libapache2-mod-wsgi-py3

Configure Apache, edit mysite.conf

SSLEngine On
          SSLProxyEngine On
          SSLProxyVerify none
          SSLProxyCheckPeerCN off
          SSLProxyCheckPeerName off
          SSLCertificateFile "opt/ssl/server.crt"
          SSLCertificateKeyFile "opt/ssl/server.key"

          ProxyRequests Off
          ProxyPreserveHost On

          ProxyPass / http://127.0.0.1:3000/
          ProxyPassReverse / http://127.0.0.1:3000/
</VirtualHost

Installing CertBot

. /venv/bin/pip install certbot

Application for certificates

. /venv/bin/certbot certonly -d mysite.conf --manual --preferred-challenges dns --server https://acme-v02.api.letsencrypt.org/directory -- config-dir /opt/ssl --work-dir /opt/ssl --logs-dir /opt/ssl

Configuring crontab

crontab -e
0 0 0 * * * * . /venv/bin/certbot certonly -d mysite.conf --manual --preferred-challenges dns --server https://acme-v02.api.letsencrypt.org/directory -- config-dir /opt/ssl --work-dir /opt/ssl --logs-dir /opt/ssl

Leave a Comment

en_USEnglish