fastcgi.rst
This file
Path
docs/deploying/fastcgi.rst
240 lines · 8.3 KiB
Last changed by
Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
History of this fileTake it
The walk stopped after 200 commits: lines older than 40745bb point at it.
Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 1–6why, one step back1.. _deploying-fastcgi:23FastCGI4=======56FastCGI is a deployment option on servers like `nginx`_, `lighttpd`_, andMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 7–10why, one step back7`cherokee`_; see :doc:`uwsgi` and :doc:`wsgi-standalone` for other options.8To use your WSGI application with any of them you will need a FastCGI9server first. The most popular one is `flup`_ which we will use for10this guide. Make sure to have it installed to follow along.Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 11–51why, one step back1112.. 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 :file:`yourapplication.fcgi` file somewhere you will find it again.44It makes sense to have that in :file:`/var/www/yourapplication` or something45similar.4647Make sure to set the executable bit on that file so that the servers48can execute it:4950.. sourcecode:: text51Add prefix for all commands in documentation (#2877)Grey Libefore adoption21b0aa6
line 52why, one step back52 $ chmod +x /var/www/yourapplication/yourapplication.fcgiMerge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 53–113why, one step back5354Configuring Apache55------------------5657The example above is good enough for a basic Apache deployment but your58`.fcgi` file will appear in your application URL e.g.59``example.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::6566 LoadModule fastcgi_module /usr/lib64/httpd/modules/mod_fastcgi.so6768 FastCgiServer /var/www/html/yourapplication/app.fcgi -idle-timeout 300 -processes 56970 <VirtualHost *>71 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>80 </VirtualHost>8182These processes will be managed by Apache. If you're using a 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::8788 FastCgiServer /var/www/html/yourapplication -host 127.0.0.1:30008990If you cannot set ScriptAlias, for example on a 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 sysRemove python 2.6 and 3.3 everywhere. (#2583)Hsiaoming Yangbefore adoption60eecb5
line 114why, one step back114 sys.path.insert(0, '<your_local_path>/lib/python<your_python_version>/site-packages')Merge pull request #2581 from pallets/config-enotdirDavid Lordbefore adoption40745bb
lines 115–239why, one step back115116 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"153 )154155Remember 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<https://redmine.lighttpd.net/projects/lighttpd/wiki/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 web servers. 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 web server 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 directory.233- The code depending on environment variables that are not set by the234 web server.235- Different python interpreters being used.236237.. _nginx: https://nginx.org/238.. _lighttpd: https://www.lighttpd.net/239.. _cherokee: http://cherokee-project.com/Merge pull request #2709 from davidism/docs-themeDavid Lordbefore adoption5fba092
line 240why, one step back240.. _flup: https://pypi.org/project/flup/