Skip to content
Myr

fastcgi.rst

This file

Path

docs/deploying/fastcgi.rst

238 lines · 8.3 KiB

Last changed by

Update cherokee links in docs/deploying (#4249)nabbisenbefore adoptionfafc132

History of this file

Take it

The walk stopped after 200 commits: lines older than e071734 point at it.

Merge pull request #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

lines 1–236why, one step back
1FastCGI
2=======34FastCGI is a deployment option on servers like `nginx`_, `lighttpd`_, and5`cherokee`_; see :doc:`uwsgi` and :doc:`wsgi-standalone` for other options.6To use your WSGI application with any of them you will need a FastCGI7server first. The most popular one is `flup`_ which we will use for8this guide. Make sure to have it installed to follow along.910.. admonition:: Watch Out1112 Please make sure in advance that any ``app.run()`` calls you might13 have in your application file are inside an ``if __name__ ==14 '__main__':`` block or moved to a separate file. Just make sure it's15 not called because this will always start a local WSGI server which16 we do not want if we deploy that application to FastCGI.1718Creating a `.fcgi` file19-----------------------2021First you need to create the FastCGI server file. Let's call it22`yourapplication.fcgi`::2324 #!/usr/bin/python25 from flup.server.fcgi import WSGIServer26 from yourapplication import app2728 if __name__ == '__main__':29 WSGIServer(app).run()3031This is enough for Apache to work, however nginx and older versions of32lighttpd need a socket to be explicitly passed to communicate with the33FastCGI server. For that to work you need to pass the path to the34socket to the :class:`~flup.server.fcgi.WSGIServer`::3536 WSGIServer(application, bindAddress='/path/to/fcgi.sock').run()3738The path has to be the exact same path you define in the server39config.4041Save the :file:`yourapplication.fcgi` file somewhere you will find it again.42It makes sense to have that in :file:`/var/www/yourapplication` or something43similar.4445Make sure to set the executable bit on that file so that the servers46can execute it:4748.. sourcecode:: text4950 $ chmod +x /var/www/yourapplication/yourapplication.fcgi5152Configuring Apache53------------------5455The example above is good enough for a basic Apache deployment but your56`.fcgi` file will appear in your application URL e.g.57``example.com/yourapplication.fcgi/news/``. There are few ways to configure58your application so that yourapplication.fcgi does not appear in the URL.59A preferable way is to use the ScriptAlias and SetHandler configuration60directives to route requests to the FastCGI server. The following example61uses FastCgiServer to start 5 instances of the application which will62handle all incoming requests::6364 LoadModule fastcgi_module /usr/lib64/httpd/modules/mod_fastcgi.so6566 FastCgiServer /var/www/html/yourapplication/app.fcgi -idle-timeout 300 -processes 56768 <VirtualHost *>69 ServerName webapp1.mydomain.com70 DocumentRoot /var/www/html/yourapplication7172 AddHandler fastcgi-script fcgi73 ScriptAlias / /var/www/html/yourapplication/app.fcgi/7475 <Location />76 SetHandler fastcgi-script77 </Location>78 </VirtualHost>7980These processes will be managed by Apache. If you're using a standalone81FastCGI server, you can use the FastCgiExternalServer directive instead.82Note that in the following the path is not real, it's simply used as an83identifier to other84directives such as AliasMatch::8586 FastCgiServer /var/www/html/yourapplication -host 127.0.0.1:30008788If you cannot set ScriptAlias, for example on a shared web host, you can use89WSGI middleware to remove yourapplication.fcgi from the URLs. Set .htaccess::9091 <IfModule mod_fcgid.c>92 AddHandler fcgid-script .fcgi93 <Files ~ (\.fcgi)>94 SetHandler fcgid-script95 Options +FollowSymLinks +ExecCGI96 </Files>97 </IfModule>9899 <IfModule mod_rewrite.c>100 Options +FollowSymlinks101 RewriteEngine On102 RewriteBase /103 RewriteCond %{REQUEST_FILENAME} !-f104 RewriteRule ^(.*)$ yourapplication.fcgi/$1 [QSA,L]105 </IfModule>106107Set yourapplication.fcgi::108109 #!/usr/bin/python110 #: optional path to your local python site-packages folder111 import sys112 sys.path.insert(0, '<your_local_path>/lib/python<your_python_version>/site-packages')113114 from flup.server.fcgi import WSGIServer115 from yourapplication import app116117 class ScriptNameStripper(object):118 def __init__(self, app):119 self.app = app120121 def __call__(self, environ, start_response):122 environ['SCRIPT_NAME'] = ''123 return self.app(environ, start_response)124125 app = ScriptNameStripper(app)126127 if __name__ == '__main__':128 WSGIServer(app).run()129130Configuring lighttpd131--------------------132133A basic FastCGI configuration for lighttpd looks like that::134135 fastcgi.server = ("/yourapplication.fcgi" =>136 ((137 "socket" => "/tmp/yourapplication-fcgi.sock",138 "bin-path" => "/var/www/yourapplication/yourapplication.fcgi",139 "check-local" => "disable",140 "max-procs" => 1141 ))142 )143144 alias.url = (145 "/static/" => "/path/to/your/static/"146 )147148 url.rewrite-once = (149 "^(/static($|/.*))$" => "$1",150 "^(/.*)$" => "/yourapplication.fcgi$1"151 )152153Remember to enable the FastCGI, alias and rewrite modules. This configuration154binds the application to ``/yourapplication``. If you want the application to155work in the URL root you have to work around a lighttpd bug with the156:class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware.157158Make sure to apply it only if you are mounting the application the URL159root. Also, see the Lighty docs for more information on `FastCGI and Python160<https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ (note that161explicitly passing a socket to run() is no longer necessary).162163Configuring nginx164-----------------165166Installing FastCGI applications on nginx is a bit different because by167default no FastCGI parameters are forwarded.168169A basic Flask FastCGI configuration for nginx looks like this::170171 location = /yourapplication { rewrite ^ /yourapplication/ last; }172 location /yourapplication { try_files $uri @yourapplication; }173 location @yourapplication {174 include fastcgi_params;175 fastcgi_split_path_info ^(/yourapplication)(.*)$;176 fastcgi_param PATH_INFO $fastcgi_path_info;177 fastcgi_param SCRIPT_NAME $fastcgi_script_name;178 fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;179 }180181This configuration binds the application to ``/yourapplication``. If you182want to have it in the URL root it's a bit simpler because you don't183have to figure out how to calculate ``PATH_INFO`` and ``SCRIPT_NAME``::184185 location / { try_files $uri @yourapplication; }186 location @yourapplication {187 include fastcgi_params;188 fastcgi_param PATH_INFO $fastcgi_script_name;189 fastcgi_param SCRIPT_NAME "";190 fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;191 }192193Running FastCGI Processes194-------------------------195196Since nginx and others do not load FastCGI apps, you have to do it by197yourself. `Supervisor can manage FastCGI processes.198<http://supervisord.org/configuration.html#fcgi-program-x-section-settings>`_199You can look around for other FastCGI process managers or write a script200to run your `.fcgi` file at boot, e.g. using a SysV ``init.d`` script.201For a temporary solution, you can always run the ``.fcgi`` script inside202GNU screen. See ``man screen`` for details, and note that this is a203manual solution which does not persist across system restart::204205 $ screen206 $ /var/www/yourapplication/yourapplication.fcgi207208Debugging209---------210211FastCGI deployments tend to be hard to debug on most web servers. Very212often the only thing the server log tells you is something along the213lines of "premature end of headers". In order to debug the application214the only thing that can really give you ideas why it breaks is switching215to the correct user and executing the application by hand.216217This example assumes your application is called `application.fcgi` and218that your web server user is `www-data`::219220 $ su www-data221 $ cd /var/www/yourapplication222 $ python application.fcgi223 Traceback (most recent call last):224 File "yourapplication.fcgi", line 4, in <module>225 ImportError: No module named yourapplication226227In this case the error seems to be "yourapplication" not being on the228python path. Common problems are:229230- Relative paths being used. Don't rely on the current working directory.231- The code depending on environment variables that are not set by the232 web server.233- Different python interpreters being used.234235.. _nginx: https://nginx.org/236.. _lighttpd: https://www.lighttpd.net/

Update cherokee links in docs/deploying (#4249)nabbisenbefore adoptionfafc132

line 237why, one step back
237.. _cherokee: https://cherokee-project.com/

Merge pull request #3734 from pallets/dependabot/pip/sphinx-3.2.1dependabot-preview[bot]before adoptione071734

line 238why, one step back
238.. _flup: https://pypi.org/project/flup/