Deploy Flask Applications with uWSGI and Lighttpd
This text is mainly documentation for me. It may apply to others, though.
In this text, I describe how you can deploy Python applications with Flask and Lighttpd. The main idea is that Lighttpd serves static files from a directory and dynamic requests from a Flask backend. This description easily translates to other backends (i.e., Tomcat). This has the advantage that you only have to configure TLS once in Lighttpd, or Lighttpd can be behind a proxy itself.
Flask and uWSGI
For this text, I assume a working Flask application (i.e., this minimal example).
First, you install uWSGI and the required Python packages using PIP: pip install uwsgi flask
.
Then, you create a user that runs uWSGI: useradd -r -m uwsgi
and place all Flask files in its directory.
Systemd is going to manage the Flask application.
Hence, you create a flask.ini
file in the app directory:
[uwsgi]
module = wsgi
master = true
processes = 3
http = 127.0.0.1:8000
The Systemd unit file looks like this:
[Unit]
Description=uWSGI server for flaskdemo
After=network.target
[Service]
User=uwsgi
Group=uwsgi
WorkingDirectory=/home/uwsgi/backend/
Environment="PATH=/home/uwsgi/backend/"
ExecStart=/home/uwsgi/backend/uwsgi --ini flask.ini
[Install]
WantedBy=multi-user.target
Now you can start uWSGI and check whether the Flask application runs correctly: systemctl start flask.service
.
If so, you enable the uWSGI service permanently systemctl enable flask.service
.
Lighttpd
In the next part, you configure Lighttpd as a proxy for uWSGI. I assume a running Lighttpd server.
You configure the proxy using the proxy module (mod_proxy
).
Therefore, you put the following in /etc/lighttpd/conf.d/proxy.conf
:
$HTTP["url"] =~ "^/app/backend/" {
proxy.header = ("map-urlpath" => ("/app/backend/" => "/"))
proxy.server = ( "" =>
(
("host" => "127.0.0.1", "port" => 8000)
)
)
}
The module rewrites all URLs that end with "/app/backend/" to "/" and redirects them to the Flask app.
To activate the proxy module, add it to the Lighttpd configuration file (/etc/lighttpd/lighttpd.conf
) and restart the webserver:
systemctl restart lighttpd.service
History of Document
- 2020-10-04 Initial text
- 2021-07-04 Move text to blog