fastcgi.rst
This file
Path
docs/deploying/fastcgi.rst
240 lines · 8.3 KiB
Last changed by
Various documentation fixupsArmin Ronacherbefore adoptiona8a98bc
History of this fileTake it
The walk stopped after 200 commits: lines older than b2cf9e7 point at it.
Merge pull request #590 from pinchsp/masterArmin Ronacherbefore adoptionb2cf9e7
lines 1–56why, one step back1.. _deploying-fastcgi:23FastCGI4=======56FastCGI is a deployment option on servers like `nginx`_, `lighttpd`_, and7`cherokee`_; see :ref:`deploying-uwsgi` and :ref:`deploying-wsgi-standalone`8for other options. To use your WSGI application with any of them you will need9a FastCGI server first. The most popular one is `flup`_ which we will use for10this guide. Make sure to have it installed to follow along.1112.. admonition:: Watch Out1314 Please make sure in advance that any ``app.run()`` calls you might15 have in your application file are inside an ``if __name__ ==16 '__main__':`` block or moved to a separate file. Just make sure it's17 not called because this will always start a local WSGI server which18 we do not want if we deploy that application to FastCGI.1920Creating a `.fcgi` file21-----------------------2223First you need to create the FastCGI server file. Let's call it24`yourapplication.fcgi`::2526 #!/usr/bin/python27 from flup.server.fcgi import WSGIServer28 from yourapplication import app2930 if __name__ == '__main__':31 WSGIServer(app).run()3233This is enough for Apache to work, however nginx and older versions of34lighttpd need a socket to be explicitly passed to communicate with the35FastCGI server. For that to work you need to pass the path to the36socket to the :class:`~flup.server.fcgi.WSGIServer`::3738 WSGIServer(application, bindAddress='/path/to/fcgi.sock').run()3940The path has to be the exact same path you define in the server41config.4243Save the `yourapplication.fcgi` file somewhere you will find it again.44It makes sense to have that in `/var/www/yourapplication` or something45similar.4647Make sure to set the executable bit on that file so that the servers48can execute it:4950.. sourcecode:: text5152 # chmod +x /var/www/yourapplication/yourapplication.fcgi5354Configuring Apache55------------------56Various documentation fixupsArmin Ronacherbefore adoptiona8a98bc
lines 57–64why, one step back57The example above is good enough for a basic Apache deployment but your58`.fcgi` file will appear in your application URL e.g.59example.com/yourapplication.fcgi/news/. There are few ways to configure60your application so that yourapplication.fcgi does not appear in the URL.61A preferable way is to use the ScriptAlias and SetHandler configuration62directives to route requests to the FastCGI server. The following example63uses FastCgiServer to start 5 instances of the application which will64handle all incoming requests::Merge pull request #590 from pinchsp/masterArmin Ronacherbefore adoptionb2cf9e7
line 65why, one step back65Update example for Apache FCGI config to use worker processes using FastCgiServer, along with some notes about FastCgiExternalServerEric Radmanbefore adoption73b4a52
lines 66–69why, one step back66 LoadModule fastcgi_module /usr/lib64/httpd/modules/mod_fastcgi.so6768 FastCgiServer /var/www/html/yourapplication/app.fcgi -idle-timeout 300 -processes 569Merge pull request #590 from pinchsp/masterArmin Ronacherbefore adoptionb2cf9e7
line 70why, one step back70 <VirtualHost *>Update example for Apache FCGI config to use worker processes using FastCgiServer, along with some notes about FastCgiExternalServerEric Radmanbefore adoption73b4a52
lines 71–79why, one step back71 ServerName webapp1.mydomain.com72 DocumentRoot /var/www/html/yourapplication7374 AddHandler fastcgi-script fcgi75 ScriptAlias / /var/www/html/yourapplication/app.fcgi/7677 <Location />78 SetHandler fastcgi-script79 </Location>Merge pull request #590 from pinchsp/masterArmin Ronacherbefore adoptionb2cf9e7
line 80why, one step back80 </VirtualHost>Update example for Apache FCGI config to use worker processes using FastCgiServer, along with some notes about FastCgiExternalServerEric Radmanbefore adoption73b4a52
line 81why, one step back81Various documentation fixupsArmin Ronacherbefore adoptiona8a98bc
lines 82–86why, one step back82These processes will be managed by Apache. If you're using an standalone83FastCGI server, you can use the FastCgiExternalServer directive instead.84Note that in the following the path is not real, it's simply used as an85identifier to other86directives such as AliasMatch::Update example for Apache FCGI config to use worker processes using FastCgiServer, along with some notes about FastCgiExternalServerEric Radmanbefore adoption73b4a52
lines 87–88why, one step back8788 FastCgiServer /var/www/html/yourapplication -host 127.0.0.1:3000Merge pull request #590 from pinchsp/masterArmin Ronacherbefore adoptionb2cf9e7
lines 89–152why, one step back8990If you cannot set ScriptAlias, for example on an shared web host, you can use91WSGI middleware to remove yourapplication.fcgi from the URLs. Set .htaccess::9293 <IfModule mod_fcgid.c>94 AddHandler fcgid-script .fcgi95 <Files ~ (\.fcgi)>96 SetHandler fcgid-script97 Options +FollowSymLinks +ExecCGI98 </Files>99 </IfModule>100101 <IfModule mod_rewrite.c>102 Options +FollowSymlinks103 RewriteEngine On104 RewriteBase /105 RewriteCond %{REQUEST_FILENAME} !-f106 RewriteRule ^(.*)$ yourapplication.fcgi/$1 [QSA,L]107 </IfModule>108109Set yourapplication.fcgi::110111 #!/usr/bin/python112 #: optional path to your local python site-packages folder113 import sys114 sys.path.insert(0, '<your_local_path>/lib/python2.6/site-packages')115116 from flup.server.fcgi import WSGIServer117 from yourapplication import app118119 class ScriptNameStripper(object):120 def __init__(self, app):121 self.app = app122123 def __call__(self, environ, start_response):124 environ['SCRIPT_NAME'] = ''125 return self.app(environ, start_response)126127 app = ScriptNameStripper(app)128129 if __name__ == '__main__':130 WSGIServer(app).run()131132Configuring lighttpd133--------------------134135A basic FastCGI configuration for lighttpd looks like that::136137 fastcgi.server = ("/yourapplication.fcgi" =>138 ((139 "socket" => "/tmp/yourapplication-fcgi.sock",140 "bin-path" => "/var/www/yourapplication/yourapplication.fcgi",141 "check-local" => "disable",142 "max-procs" => 1143 ))144 )145146 alias.url = (147 "/static/" => "/path/to/your/static"148 )149150 url.rewrite-once = (151 "^(/static($|/.*))$" => "$1",152 "^(/.*)$" => "/yourapplication.fcgi$1"Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption51d7c8d
line 153why, one step back153 )Merge pull request #590 from pinchsp/masterArmin Ronacherbefore adoptionb2cf9e7
lines 154–240why, one step back154155Remember to enable the FastCGI, alias and rewrite modules. This configuration156binds the application to `/yourapplication`. If you want the application to157work in the URL root you have to work around a lighttpd bug with the158:class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware.159160Make sure to apply it only if you are mounting the application the URL161root. Also, see the Lighty docs for more information on `FastCGI and Python162<http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModFastCGI>`_ (note that163explicitly passing a socket to run() is no longer necessary).164165Configuring nginx166-----------------167168Installing FastCGI applications on nginx is a bit different because by169default no FastCGI parameters are forwarded.170171A basic flask FastCGI configuration for nginx looks like this::172173 location = /yourapplication { rewrite ^ /yourapplication/ last; }174 location /yourapplication { try_files $uri @yourapplication; }175 location @yourapplication {176 include fastcgi_params;177 fastcgi_split_path_info ^(/yourapplication)(.*)$;178 fastcgi_param PATH_INFO $fastcgi_path_info;179 fastcgi_param SCRIPT_NAME $fastcgi_script_name;180 fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;181 }182183This configuration binds the application to `/yourapplication`. If you184want to have it in the URL root it's a bit simpler because you don't185have to figure out how to calculate `PATH_INFO` and `SCRIPT_NAME`::186187 location / { try_files $uri @yourapplication; }188 location @yourapplication {189 include fastcgi_params;190 fastcgi_param PATH_INFO $fastcgi_script_name;191 fastcgi_param SCRIPT_NAME "";192 fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;193 }194195Running FastCGI Processes196-------------------------197198Since Nginx and others do not load FastCGI apps, you have to do it by199yourself. `Supervisor can manage FastCGI processes.200<http://supervisord.org/configuration.html#fcgi-program-x-section-settings>`_201You can look around for other FastCGI process managers or write a script202to run your `.fcgi` file at boot, e.g. using a SysV ``init.d`` script.203For a temporary solution, you can always run the ``.fcgi`` script inside204GNU screen. See ``man screen`` for details, and note that this is a205manual solution which does not persist across system restart::206207 $ screen208 $ /var/www/yourapplication/yourapplication.fcgi209210Debugging211---------212213FastCGI deployments tend to be hard to debug on most webservers. Very214often the only thing the server log tells you is something along the215lines of "premature end of headers". In order to debug the application216the only thing that can really give you ideas why it breaks is switching217to the correct user and executing the application by hand.218219This example assumes your application is called `application.fcgi` and220that your webserver user is `www-data`::221222 $ su www-data223 $ cd /var/www/yourapplication224 $ python application.fcgi225 Traceback (most recent call last):226 File "yourapplication.fcgi", line 4, in <module>227 ImportError: No module named yourapplication228229In this case the error seems to be "yourapplication" not being on the230python path. Common problems are:231232- Relative paths being used. Don't rely on the current working directory233- The code depending on environment variables that are not set by the234 web server.235- Different python interpreters being used.236237.. _nginx: http://nginx.org/238.. _lighttpd: http://www.lighttpd.net/239.. _cherokee: http://www.cherokee-project.com/240.. _flup: http://trac.saddi.com/flup