Setting Up an HTTPS Reverse Proxy for Uvicorn with Apache
Uvicorn is a Python web server and development server that supports many frameworks, including Flask, Django, and FastAPI. Developers love Uvicorn for its high performance and ease of use.
1. Installing Uvicorn
Install venv for your local Python:
# apt install python-venv
To keep things isolated from root, create a regular user named mysiteuser:
# useradd -m mysiteuser
# passwd mysite
Log in via SSH as mysiteuser:
ssh mysiteuser@123.123.123.123
Create a Python virtual environment:
$ python -m venv ./venv
Install uvicorn in the virtual environment:
$./venv/bin/pip install uvicorn
Uvicorn configuration. Here is an example mymodule.py for running a Flask app:
#!/bin/python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
if __name__ == '__main__':
uvicorn.run(app,host='0.0.0.0',port=3000)
Start the server with the following command:
./venv/bin/uvicorn mymodule:app --reload
Here, mymodule is the name of the Python module containing your Flask application.
2. Installing Apache
Apache's configuration files are located in /etc/apache2/sites-available/
Create the file mysite.conf:
<VirtualHost *:80>
</VirtualHost>
Save the configuration and enable it:
a2ensite mysite.conf
Restart Apache to apply the changes:
systemctl restart apache2
3. Integration
Install wsgi support for apache2:
apt-get install libapache2-mod-wsgi-py3
Configure Apache by editing mysite.conf:
<VirtualHost *:80>
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>
Install CertBot:
./venv/bin/pip install certbot
Request a certificate:
./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
Configure 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