Proxies with Apache and python

2014-10-09 python apache proxy gunicorn uwsgi

This is a quick note on proxying a local python application (e.g. flask) to a subdirectory in Apache. This assumes that the file wsgi.py contains a WSGI application with the name application. Hence, wsgi:application.

Gunicorn

1
2
3
4
5
<Location /myapp/>
    ProxyPass http://127.0.0.1:8888/myapp/
    ProxyPassReverse http://127.0.0.1:8888/myapp/
    RequestHeader set SCRIPT_NAME "/myapp/"
</Location>

Important: SCRIPT_NAME and the end of ProxyPass URL MUST BE THE SAME. Otherwise, Gunicorn will fail miserably.

Try it with:

1
venv/bin/gunicorn -w 4 -b 127.0.0.1:8888 --log-file - --access-logfile - wsgi:application

UWSGI

This is a very simple configuration. I will try to upload one with more options for uwsgi (in a .ini file).

1
2
3
4
<Location /myapp/>
    SetHandler uwsgi_handler
    uWSGISocker 127.0.0.1:8888
</Location>

Try it with:

1
uwsgi --socket 127.0.0.1:8888 -w wsgi:application

Extra: Supervisor

If everything went as expected, you can wrap your command in a supervisor config file and let it handle the server for you.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
[unix_http_server]
file=/tmp/myapp.sock ; path to your socket file

[supervisord]
logfile = %(here)s/logs/supervisor.log
childlogdir = %(here)s/logs/

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
logfile = %(here)s/logs/supervisorctl.log
serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL for a unix socket

[program:myapp]
command = venv/bin/gunicorn -w 4 -b 0.0.0.0:5000 --log-file %(here)s/logs/gunicorn.log --access-logfile - wsgi:application
directory = %(here)s
environment = PATH=%(here)s/venv/bin/
logfile = %(here)s/logs/myapp.log