Skip to content
Myr

deploying.rst

This file

Path

docs/deploying.rst

307 lines · 9.7 KiB

Last changed by

Reordered deployment docsArmin Ronacherbefore adoptionb9cae35

History of this file

Take it

1Deployment Options2==================34Depending on what you have available there are multiple ways to run Flask5applications.  A very common method is to use the builtin server during6development and maybe behind a proxy for simple applications, but there7are more options available.89If you have a different WSGI server look up the server documentation about10how to use a WSGI app with it.  Just remember that your application object11is the actual WSGI application.121314mod_wsgi (Apache)15-----------------1617If you are using the `Apache`_ webserver you should consider using `mod_wsgi`_.1819.. _Apache: http://httpd.apache.org/2021Installing `mod_wsgi`22`````````````````````2324If you don't have `mod_wsgi` installed yet you have to either install it using25a package manager or compile it yourself.2627The mod_wsgi `installation instructions`_ cover installation instructions for28source installations on UNIX systems.2930If you are using ubuntu / debian you can apt-get it and activate it as follows::3132    # apt-get install libapache2-mod-wsgi3334On FreeBSD install `mod_wsgi` by compiling the `www/mod_wsgi` port or by using35pkg_add::3637    # pkg_add -r mod_wsgi3839If you are using pkgsrc you can install `mod_wsgi` by compiling the40`www/ap2-wsgi` package.4142If you encounter segfaulting child processes after the first apache reload you43can safely ignore them.  Just restart the server.4445Creating a `.wsgi` file46```````````````````````4748To run your application you need a `yourapplication.wsgi` file.  This file49contains the code `mod_wsgi` is executing on startup to get the application50object.  The object called `application` in that file is then used as51application.5253For most applications the following file should be sufficient::5455    from yourapplication import app as application5657If you don't have a factory function for application creation but a singleton58instance you can directly import that one as `application`.5960Store that file somewhere where you will find it again (eg:61`/var/www/yourapplication`) and make sure that `yourapplication` and all62the libraries that are in use are on the python load path.  If you don't63want to install it system wide consider using a `virtual python`_ instance.6465Configuring Apache66``````````````````6768The last thing you have to do is to create an Apache configuration file for69your application.  In this example we are telling `mod_wsgi` to execute the70application under a different user for security reasons:7172.. sourcecode:: apache7374    <VirtualHost *>75        ServerName example.com7677        WSGIDaemonProcess yourapplication user=user1 group=group1 threads=578        WSGIScriptAlias / /var/www/yourapplication/yourapplication.wsgi7980        <Directory /var/www/yourapplication>81            WSGIProcessGroup yourapplication82            WSGIApplicationGroup %{GLOBAL}83            Order deny,allow84            Allow from all85        </Directory>86    </VirtualHost>8788For more information consult the `mod_wsgi wiki`_.8990.. _mod_wsgi: http://code.google.com/p/modwsgi/91.. _installation instructions: http://code.google.com/p/modwsgi/wiki/QuickInstallationGuide92.. _virtual python: http://pypi.python.org/pypi/virtualenv93.. _mod_wsgi wiki: http://code.google.com/p/modwsgi/wiki/949596CGI97---9899If all other deployment methods do not work, CGI will work for sure.  CGI100is supported by all major servers but usually has a less-than-optimal101performance.102103This is also the way you can use a Flask application on Google's104`AppEngine`_, there however the execution does happen in a CGI-like105environment.  The application's performance is unaffected because of that.106107.. _AppEngine: http://code.google.com/appengine/108109Creating a `.cgi` file110``````````````````````111112First you need to create the CGI application file.  Let's call it113`yourapplication.cgi`::114115    #!/usr/bin/python116    from wsgiref.handlers import CGIHandler117    from yourapplication import app118119    CGIHandler().run(app)120121If you're running Python 2.4 you will need the :mod:`wsgiref` package.  Python1222.5 and higher ship this as part of the standard library.123124Server Setup125````````````126127Usually there are two ways to configure the server.  Either just copy the128`.cgi` into a `cgi-bin` (and use `mod_rerwite` or something similar to129rewrite the URL) or let the server point to the file directly.130131In Apache for example you can put a like like this into the config:132133.. sourcecode:: apache134135    ScriptName /app /path/to/the/application.cgi136137For more information consult the documentation of your webserver.138139140141FastCGI142-------143144A very popular deployment setup on servers like `lighttpd`_ and `nginx`_145is FastCGI.  To use your WSGI application with any of them you will need146a FastCGI server first.147148The most popular one is `flup`_ which we will use for this guide.  Make149sure to have it installed.150151Creating a `.fcgi` file152```````````````````````153154First you need to create the FastCGI server file.  Let's call it155`yourapplication.fcgi`::156157    #!/usr/bin/python158    from flup.server.fcgi import WSGIServer159    from yourapplication import app160161    WSGIServer(app).run()162163This is enough for Apache to work, however lighttpd and nginx need a164socket to communicate with the FastCGI server.  For that to work you165need to pass the path to the socket to the166:class:`~flup.server.fcgi.WSGIServer`::167168    WSGIServer(application, bindAddress='/path/to/fcgi.sock').run()169170The path has to be the exact same path you define in the server171config.172173Save the `yourapplication.fcgi` file somewhere you will find it again.174It makes sense to have that in `/var/www/yourapplication` or something175similar.176177Make sure to set the executable bit on that file so that the servers178can execute it::179180    # chmod +x /var/www/yourapplication/yourapplication.fcgi181182Configuring lighttpd183````````````````````184185A basic FastCGI configuration for lighttpd looks like that::186187    fastcgi.server = ("/yourapplication" =>188        "yourapplication" => (189            "socket" => "/tmp/yourapplication-fcgi.sock",190            "bin-path" => "/var/www/yourapplication/yourapplication.fcgi",191            "check-local" => "disable"192        )193    )194195This configuration binds the application to `/yourapplication`.  If you196want the application to work in the URL root you have to work around a197lighttpd bug with the :class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix`198middleware.199200Make sure to apply it only if you are mounting the application the URL201root.202203Configuring nginx204`````````````````205206Installing FastCGI applications on nginx is a bit tricky because by default207some FastCGI parameters are not properly forwarded.208209A basic FastCGI configuration for nginx looks like this::210211    location /yourapplication/ {212        include fastcgi_params;213        if ($uri ~ ^/yourapplication/(.*)?) {214            set $path_url $1;215        }216        fastcgi_param PATH_INFO $path_url;217        fastcgi_param SCRIPT_NAME /yourapplication;218        fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;219    }220221This configuration binds the application to `/yourapplication`.  If you want222to have it in the URL root it's a bit easier because you don't have to figure223out how to calculate `PATH_INFO` and `SCRIPT_NAME`::224225    location /yourapplication/ {226        include fastcgi_params;227        fastcgi_param PATH_INFO $fastcgi_script_name;228        fastcgi_param SCRIPT_NAME "";229        fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;230    }231232Since Nginx doesn't load FastCGI apps, you have to do it by yourself.  You233can either write an `init.d` script for that or execute it inside a screen234session::235236    $ screen237    $ /var/www/yourapplication/yourapplication.fcgi238239Debugging240`````````241242FastCGI deployments tend to be hard to debug on most webservers.  Very often the243only thing the server log tells you is something along the lines of "premature244end of headers".  In order to debug the application the only thing that can245really give you ideas why it breaks is switching to the correct user and246executing the application by hand.247248This example assumes your application is called `application.fcgi` and that your249webserver user is `www-data`::250251    $ su www-data252    $ cd /var/www/yourapplication253    $ python application.fcgi254    Traceback (most recent call last):255      File "yourapplication.fcg", line 4, in <module>256    ImportError: No module named yourapplication257258In this case the error seems to be "yourapplication" not being on the python259path.  Common problems are:260261-   relative paths being used.  Don't rely on the current working directory262-   the code depending on environment variables that are not set by the263    web server.264-   different python interpreters being used.265266.. _lighttpd: http://www.lighttpd.net/267.. _nginx: http://nginx.net/268.. _flup: http://trac.saddi.com/flup269270271272Tornado273--------274275`Tornado`_ is an open source version of the scalable, non-blocking web server and tools that power `FriendFeed`_.276Because it is non-blocking and uses epoll, it can handle thousands of simultaneous standing connections, which means it is ideal for real-time web services.277Integrating this service with Flask is a trivial task::278279    280    from tornado.wsgi import WSGIContainer281    from tornado.httpserver import HTTPServer282    from tornado.ioloop import IOLoop283    from yourapplication import app284    285    http_server = HTTPServer(WSGIContainer(app))286    http_server.listen(5000)287    IOLoop.instance().start()288289290.. _Tornado: http://www.tornadoweb.org/291.. _FriendFeed: http://friendfeed.com/292293294Gevent295-------296297`Gevent`_ is a coroutine-based Python networking library that uses `greenlet`_ to provide a high-level synchronous API on top of `libevent`_ event loop::298299    from gevent.wsgi import WSGIServer300    from yourapplication import app301302    http_server = WSGIServer(('', 5000), app)303    http_server.serve_forever()304305.. _Gevent: http://www.gevent.org/306.. _greenlet: http://codespeak.net/py/0.9.2/greenlet.html307.. _libevent: http://monkey.org/~provos/libevent/