Deploying Flask applications with mod_wsgi
can be tricky. I hope this post makes it
clear for you!
Let's suppose you just want to develop, and proof-of-concept your application with
mod_wsgi
. One of the core developers of mod_wsgi
has put together a set of
potentially "production ready" Dockerfile's. Whether or not these are production
ready, it certainly removes the substantial overhead of learning how to configure apache
and mod_wsgi
.
Create a Dockerfile
something like this:
FROM grahamdumpleton/mod-wsgi-docker:python-3.5-onbuild USER
$MOD_WSGI_USER:$MOD_WSGI_GROUP CMD [ "/app/wsgi.py" ]
Create a wsgi.py
file something like this:
import os from myapp_module import create_app
application = create_app(os.environ.get('APP_MODE'))
As far as I have been able to tell the only thing you really need is a Python module, that
has an application
object defined in it.
Then to build and run this Dockerfile
:
$ docker image build -t modwsgi . $ docker container run -it --rm -p 8000:80 -d
--name modwsgi modwsgi
Visit localhost:8000
, and profit💰. Don't forget to stop the container when you are
done (docker container stop
).
What if you can't use Docker, no problem! It requires a bit more work, but don't worry.
This documentation on virtualenv
is important. Also the Flask docs have a section
on mod_wsgi that is very relevant.
This wsgi.py
file becomes this for Python 3 (for Python):
import os
activate_this = '/path/to/env/bin/activate_this.py' with open(activate_this) as file_:
exec(file_.read(), dict(__file__=activate_this))
from myapp_module import create_app
application = create_app(os.environ.get('APP_MODE'))
activate_this.py
?It is a file that virtualenv
sets up for you. Note: python3.5 -m venv venv
does
not create this file!
Recall that creating a virtual environment goes like this:
$ virtualenv -p python3 venv $ virtualenv -p python2 venv
If you look in the venv/bin/
directory you'll see activate_this.py
.
I'm taking the easy way out here. I'm not going to explain how to set up Apache and
mod_wsgi
. I don't know how to :) right now. There are plenty of tutorials out there
for that.
But eventually mod_wsgi
will be looking for wsgi.py
set up as above.
Note: mod_wsgi
can read from .py
files, but it seems to be a standard to read from
.wsgi
files (but they are just Python files AFAICT).