This is the final part of my tutorial on Flask Server Deployment. In the last section we configured our Gunicorn WSGI server and controlled it via Supervisor. In this section we will place our WSGI server behind a Proxy server.
This is the question I asked me first when I read in the Gunicorn documentation that one should put the Gunicorn application server behind a proxy. Mainly the main advantages of a proxy seem to be:
The guys from Gunicorn recommend Nginx as a proxy so I decided to follow this recommendation. One could also use Apache here.
We install Nginx via apt-get:
apt-get install nginx
The configuration happens mainly via the /etc/nginx/nginx.conf file. We open it with our editor and add our server configuration:
server {
listen 80;
server_name _;
access_log /var/log/nginx/flaskapp.log;
error_log /var/log/nginx/flaskapp_err.log;
location / {
proxy_pass http://127.0.0.1:8000/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
What we do now is listen on port 80 for any requests. Those requests are passed on to port 8000 of our localhost. This is where our Gunicorn server will serve our flasktest app. The proxy_set_header directives are used to rewrite the headers so that our application works behind a proxy. Before we start of with our new proxy configuration make sure you changed the port in our Gunicorn startup script /home/apps/run_flaskapp.py from 80 to 8000 and restart it with
supervisorctl restart flasktest
Now we restart our nginx server:
service nginx restart
Now we will see our "Hello World" statement served from a WSGI application server behind a proxy.