links

contact

Deploying a Flask web application on FreeBSD • 20 Feb 2013

Go web scale with Flask!
Flask is a small framework which can be used to build web applications.
It also has good documentation.
Flask's built-in webserver is only usable for development, so for production purposes I use
gunicorn as the webserver.
It will run a few instances of the web application in a few worker threads.
Nginx as a reverse-proxy is used to free the worker threads from requests by slow clients (like mobile phones).
And lastly, supervisor is used to monitor the web application and restart it, should it terminate for some reason.
It also starts the web application when the server reboots.

Flask and the web application

Install FreeBSD on a machine. Become root and install Python if it's not already installed. Then install pip and Flask (via pip). Alternatively, you could install the port /usr/ports/www/py-flask.

# cd /usr/ports/devel/py-pip
# make install clean
# pip install flask

This is the source code of the example web application (in this article, it lives in /usr/home/user/prj/python/flask-examples/example2.py):

...point a webbrowser, preferably on another machine, to http://SERVER:5000/, where SERVER is the IP address of the machine you run the web application on, and the app should respond with something like this:

Hello, 192.168.5.30

Ok, the webapp works. But it still uses the built-in development webserver which is not suitable for production environments.

Gunicorn

Let's start a real webserver and create 4 worker-threads for the web application.
First, install gunicorn, either by installing the port www/py-gunicorn or via pip:

If you now point your webbrowser to http://SERVER:81, you'll get a 'Bad Gateway' error from nginx, because the web application is not running.

Supervisor

We have to make our web application controllable by a monitoring program. Should the web application crash for some reason, it has to be restarted. Also in the case of a server reboot, it must be started. Supervisor does the job.

# cd /usr/ports/sysutils/py-supervisord
# make install clean

And put this in /etc/rc.conf:

supervisord_enable="yes"

Add the web application to /usr/local/etc/supervisord.conf as 'flaskexample':

Comments

JoongSeob vito kim • 11 Jul 2013

Nice post. It helps much! Thank you.

Jordan • 19 Jul 2014

Thanks for the guide!

Gerald • 8 Dec 2014

Thank you very much. It is extreme helpful.

Dani • 1 Oct 2015

Awesome man!

Dude • 30 Mar 2017

svn checkout and update makes a fully functional workcopy including files in .svn dir, you don't need it on production so use svn export instead to get only project files without any unnecessary things