Every web app we've designed has used Flask's built in webs server. This has worked well for development and debugging, but there are serious drawbacks to using it as the full-time server for a live website.
The web server is single-threaded. This means all requests (including html, css, js, images, ajax calls...) are handled sequentially. Every visitor to your site has to wait for any previous requests to resolve before theirs.
It is not designed to protect your application and server machine from malicious attacks.
It is not designed to be a long term high volume server, and could fail for various reasons while the site is live.
Production web servers are designed to handle large number of requests. Commonly this is done by using separate processes or threads for each request. These processes/threads are often called workers.
Production servers also can run multiple sites using different domain names on the same machine.
Common Production Servers
- apache2
- nginx
- green unicorn
- very lightweight web server that requires little in the way of configuration, not as robust as apache2 or nginx
Each unique site (distinct domain name) is a Virtual Host.
All processes have run under the username and group: www-data
.
This is important if your app creates/writes/modifies local files.
Configuration files live in /etc/apache2/
.
Websites live in /var/www/
.
We want Apache2 to be our web server, but we still want to use our flask code as our site backend.
Web Server Gateway Interface (WSGI) is a convention (set of common function names) that allows conventional web servers to forward requests to python based frameworks and applications.
- Install apache2
$ sudo apt-get install apache2
(always run $sudo apt-get update
before installing)
- Install and enable
mod_wsgi
$ sudo apt-get install libapache2-mod-wsgi
$ sudo a2enmod wsgi
$ sudo service apache2 restart
- Rename your flask app file to
init.py
. Make sure your entire flask structure is in a single directory named after your application. In that directory, create a file called<appname>.wsgi
.
GGgallery/
GGGallery.wsgi
GGGallery/
__init__.py
static/
templates/
utils/
WSGI file
#!/usr/bin/python
import sys
sys.path.insert(0, "/var/www/GGgallery/")
from GGgallery import app as application
Apache site config file
<VirtualHost *:80>
ServerName deploytest.stuycs.org
WSGIScriptAlias / /var/www/deploytest/deploytest.wsgi
<Directory /var/www/deploytest/deploytest/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/deploytest/deploytest/static
<Directory /var/www/deploytest/deploytest/static/>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
$ sudo cp <appname>.conf /etc/apache2/sites-available
$ sudo a2enmod <appname>
$ sudo service apache2 restart
To view logs
$ sudo cat /var/log/apache2/...