PageRenderTime 52ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/docs/howto/deployment/fastcgi.txt

https://code.google.com/p/mango-py/
Plain Text | 399 lines | 293 code | 106 blank | 0 comment | 0 complexity | c51587b49af89405a5de13eb018e5c3c MD5 | raw file
Possible License(s): BSD-3-Clause
  1. ============================================
  2. How to use Django with FastCGI, SCGI, or AJP
  3. ============================================
  4. .. highlight:: bash
  5. Although the current preferred setup for running Django is :doc:`Apache with
  6. mod_wsgi </howto/deployment/modwsgi>`, many people use shared hosting, on
  7. which protocols such as FastCGI, SCGI or AJP are the only viable options. In
  8. some setups, these protocols may provide better performance than mod_wsgi_.
  9. .. admonition:: Note
  10. This document primarily focuses on FastCGI. Other protocols, such as SCGI
  11. and AJP, are also supported, through the ``flup`` Python package. See the
  12. Protocols_ section below for specifics about SCGI and AJP.
  13. Essentially, FastCGI is an efficient way of letting an external application
  14. serve pages to a Web server. The Web server delegates the incoming Web requests
  15. (via a socket) to FastCGI, which executes the code and passes the response back
  16. to the Web server, which, in turn, passes it back to the client's Web browser.
  17. Like mod_wsgi, FastCGI allows code to stay in memory, allowing requests to be
  18. served with no startup time. While mod_wsgi can either be configured embedded
  19. in the Apache Web server process or as a separate daemon process, a FastCGI
  20. process never runs inside the Web server process, always in a separate,
  21. persistent process.
  22. .. _mod_wsgi: http://code.google.com/p/modwsgi/
  23. .. _mod_perl: http://perl.apache.org/
  24. .. admonition:: Why run code in a separate process?
  25. The traditional ``mod_*`` arrangements in Apache embed various scripting
  26. languages (most notably PHP, Python and Perl) inside the process space of
  27. your Web server. Although this lowers startup time -- because code doesn't
  28. have to be read off disk for every request -- it comes at the cost of
  29. memory use.
  30. Due to the nature of FastCGI, it's even possible to have processes that run
  31. under a different user account than the Web server process. That's a nice
  32. security benefit on shared systems, because it means you can secure your
  33. code from other users.
  34. Prerequisite: flup
  35. ==================
  36. Before you can start using FastCGI with Django, you'll need to install flup_, a
  37. Python library for dealing with FastCGI. Version 0.5 or newer should work fine.
  38. .. _flup: http://www.saddi.com/software/flup/
  39. Starting your FastCGI server
  40. ============================
  41. FastCGI operates on a client-server model, and in most cases you'll be starting
  42. the FastCGI process on your own. Your Web server (be it Apache, lighttpd, or
  43. otherwise) only contacts your Django-FastCGI process when the server needs a
  44. dynamic page to be loaded. Because the daemon is already running with the code
  45. in memory, it's able to serve the response very quickly.
  46. .. admonition:: Note
  47. If you're on a shared hosting system, you'll probably be forced to use
  48. Web server-managed FastCGI processes. See the section below on running
  49. Django with Web server-managed processes for more information.
  50. A Web server can connect to a FastCGI server in one of two ways: It can use
  51. either a Unix domain socket (a "named pipe" on Win32 systems), or it can use a
  52. TCP socket. What you choose is a manner of preference; a TCP socket is usually
  53. easier due to permissions issues.
  54. To start your server, first change into the directory of your project (wherever
  55. your :doc:`manage.py </ref/django-admin>` is), and then run the
  56. :djadmin:`runfcgi` command::
  57. ./manage.py runfcgi [options]
  58. If you specify ``help`` as the only option after :djadmin:`runfcgi`, it'll
  59. display a list of all the available options.
  60. You'll need to specify either a :djadminopt:`socket`, a :djadminopt:`protocol`
  61. or both :djadminopt:`host` and :djadminopt:`port`. Then, when you set up your
  62. Web server, you'll just need to point it at the host/port or socket you
  63. specified when starting the FastCGI server. See the examples_, below.
  64. Protocols
  65. ---------
  66. Django supports all the protocols that flup_ does, namely fastcgi_, `SCGI`_ and
  67. `AJP1.3`_ (the Apache JServ Protocol, version 1.3). Select your preferred
  68. protocol by using the :djadminopt:`protocol=\<protocol_name\> <protocol>` option
  69. with ``./manage.py runfcgi`` -- where ``<protocol_name>`` may be one of:
  70. ``fcgi`` (the default), ``scgi`` or ``ajp``. For example::
  71. ./manage.py runfcgi protocol=scgi
  72. .. _flup: http://www.saddi.com/software/flup/
  73. .. _fastcgi: http://www.fastcgi.com/
  74. .. _SCGI: http://python.ca/scgi/protocol.txt
  75. .. _AJP1.3: http://tomcat.apache.org/connectors-doc/ajp/ajpv13a.html
  76. Examples
  77. --------
  78. Running a threaded server on a TCP port::
  79. ./manage.py runfcgi method=threaded host=127.0.0.1 port=3033
  80. Running a preforked server on a Unix domain socket::
  81. ./manage.py runfcgi method=prefork socket=/home/user/mysite.sock pidfile=django.pid
  82. .. admonition:: Socket security
  83. Django's default umask requires that the webserver and the Django fastcgi
  84. process be run with the same group **and** user. For increased security,
  85. you can run them under the same group but as different users. If you do
  86. this, you will need to set the umask to 0002 using the ``umask`` argument
  87. to ``runfcgi``.
  88. Run without daemonizing (backgrounding) the process (good for debugging)::
  89. ./manage.py runfcgi daemonize=false socket=/tmp/mysite.sock maxrequests=1
  90. Stopping the FastCGI daemon
  91. ---------------------------
  92. If you have the process running in the foreground, it's easy enough to stop it:
  93. Simply hitting ``Ctrl-C`` will stop and quit the FastCGI server. However, when
  94. you're dealing with background processes, you'll need to resort to the Unix
  95. ``kill`` command.
  96. If you specify the :djadminopt:`pidfile` option to :djadmin:`runfcgi`, you can
  97. kill the running FastCGI daemon like this::
  98. kill `cat $PIDFILE`
  99. ...where ``$PIDFILE`` is the ``pidfile`` you specified.
  100. To easily restart your FastCGI daemon on Unix, try this small shell script::
  101. #!/bin/bash
  102. # Replace these three settings.
  103. PROJDIR="/home/user/myproject"
  104. PIDFILE="$PROJDIR/mysite.pid"
  105. SOCKET="$PROJDIR/mysite.sock"
  106. cd $PROJDIR
  107. if [ -f $PIDFILE ]; then
  108. kill `cat -- $PIDFILE`
  109. rm -f -- $PIDFILE
  110. fi
  111. exec /usr/bin/env - \
  112. PYTHONPATH="../python:.." \
  113. ./manage.py runfcgi socket=$SOCKET pidfile=$PIDFILE
  114. Apache setup
  115. ============
  116. To use Django with Apache and FastCGI, you'll need Apache installed and
  117. configured, with `mod_fastcgi`_ installed and enabled. Consult the Apache
  118. documentation for instructions.
  119. Once you've got that set up, point Apache at your Django FastCGI instance by
  120. editing the ``httpd.conf`` (Apache configuration) file. You'll need to do two
  121. things:
  122. * Use the ``FastCGIExternalServer`` directive to specify the location of
  123. your FastCGI server.
  124. * Use ``mod_rewrite`` to point URLs at FastCGI as appropriate.
  125. .. _mod_fastcgi: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html
  126. Specifying the location of the FastCGI server
  127. ---------------------------------------------
  128. The ``FastCGIExternalServer`` directive tells Apache how to find your FastCGI
  129. server. As the `FastCGIExternalServer docs`_ explain, you can specify either a
  130. ``socket`` or a ``host``. Here are examples of both:
  131. .. code-block:: apache
  132. # Connect to FastCGI via a socket / named pipe.
  133. FastCGIExternalServer /home/user/public_html/mysite.fcgi -socket /home/user/mysite.sock
  134. # Connect to FastCGI via a TCP host/port.
  135. FastCGIExternalServer /home/user/public_html/mysite.fcgi -host 127.0.0.1:3033
  136. In either case, the file ``/home/user/public_html/mysite.fcgi`` doesn't
  137. actually have to exist. It's just a URL used by the Web server internally -- a
  138. hook for signifying which requests at a URL should be handled by FastCGI. (More
  139. on this in the next section.)
  140. .. _FastCGIExternalServer docs: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html#FastCgiExternalServer
  141. Using mod_rewrite to point URLs at FastCGI
  142. ------------------------------------------
  143. The second step is telling Apache to use FastCGI for URLs that match a certain
  144. pattern. To do this, use the `mod_rewrite`_ module and rewrite URLs to
  145. ``mysite.fcgi`` (or whatever you specified in the ``FastCGIExternalServer``
  146. directive, as explained in the previous section).
  147. In this example, we tell Apache to use FastCGI to handle any request that
  148. doesn't represent a file on the filesystem and doesn't start with ``/media/``.
  149. This is probably the most common case, if you're using Django's admin site:
  150. .. code-block:: apache
  151. <VirtualHost 12.34.56.78>
  152. ServerName example.com
  153. DocumentRoot /home/user/public_html
  154. Alias /media /home/user/python/django/contrib/admin/media
  155. RewriteEngine On
  156. RewriteRule ^/(media.*)$ /$1 [QSA,L,PT]
  157. RewriteCond %{REQUEST_FILENAME} !-f
  158. RewriteRule ^/(.*)$ /mysite.fcgi/$1 [QSA,L]
  159. </VirtualHost>
  160. .. _mod_rewrite: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
  161. Django will automatically use the pre-rewrite version of the URL when
  162. constructing URLs with the ``{% url %}`` template tag (and similar methods).
  163. lighttpd setup
  164. ==============
  165. lighttpd_ is a lightweight Web server commonly used for serving static files. It
  166. supports FastCGI natively and, thus, is a good choice for serving both static
  167. and dynamic pages, if your site doesn't have any Apache-specific needs.
  168. .. _lighttpd: http://www.lighttpd.net/
  169. Make sure ``mod_fastcgi`` is in your modules list, somewhere after
  170. ``mod_rewrite`` and ``mod_access``, but not after ``mod_accesslog``. You'll
  171. probably want ``mod_alias`` as well, for serving admin media.
  172. Add the following to your lighttpd config file:
  173. .. code-block:: lua
  174. server.document-root = "/home/user/public_html"
  175. fastcgi.server = (
  176. "/mysite.fcgi" => (
  177. "main" => (
  178. # Use host / port instead of socket for TCP fastcgi
  179. # "host" => "127.0.0.1",
  180. # "port" => 3033,
  181. "socket" => "/home/user/mysite.sock",
  182. "check-local" => "disable",
  183. )
  184. ),
  185. )
  186. alias.url = (
  187. "/media" => "/home/user/django/contrib/admin/media/",
  188. )
  189. url.rewrite-once = (
  190. "^(/media.*)$" => "$1",
  191. "^/favicon\.ico$" => "/media/favicon.ico",
  192. "^(/.*)$" => "/mysite.fcgi$1",
  193. )
  194. Running multiple Django sites on one lighttpd
  195. ---------------------------------------------
  196. lighttpd lets you use "conditional configuration" to allow configuration to be
  197. customized per host. To specify multiple FastCGI sites, just add a conditional
  198. block around your FastCGI config for each site::
  199. # If the hostname is 'www.example1.com'...
  200. $HTTP["host"] == "www.example1.com" {
  201. server.document-root = "/foo/site1"
  202. fastcgi.server = (
  203. ...
  204. )
  205. ...
  206. }
  207. # If the hostname is 'www.example2.com'...
  208. $HTTP["host"] == "www.example2.com" {
  209. server.document-root = "/foo/site2"
  210. fastcgi.server = (
  211. ...
  212. )
  213. ...
  214. }
  215. You can also run multiple Django installations on the same site simply by
  216. specifying multiple entries in the ``fastcgi.server`` directive. Add one
  217. FastCGI host for each.
  218. Cherokee setup
  219. ==============
  220. Cherokee is a very fast, flexible and easy to configure Web Server. It
  221. supports the widespread technologies nowadays: FastCGI, SCGI, PHP, CGI, SSI,
  222. TLS and SSL encrypted connections, Virtual hosts, Authentication, on the fly
  223. encoding, Load Balancing, Apache compatible log files, Data Base Balancer,
  224. Reverse HTTP Proxy and much more.
  225. The Cherokee project provides a documentation to `setting up Django`_ with Cherokee.
  226. .. _setting up Django: http://www.cherokee-project.com/doc/cookbook_django.html
  227. Running Django on a shared-hosting provider with Apache
  228. =======================================================
  229. Many shared-hosting providers don't allow you to run your own server daemons or
  230. edit the ``httpd.conf`` file. In these cases, it's still possible to run Django
  231. using Web server-spawned processes.
  232. .. admonition:: Note
  233. If you're using Web server-spawned processes, as explained in this section,
  234. there's no need for you to start the FastCGI server on your own. Apache
  235. will spawn a number of processes, scaling as it needs to.
  236. In your Web root directory, add this to a file named ``.htaccess``:
  237. .. code-block:: apache
  238. AddHandler fastcgi-script .fcgi
  239. RewriteEngine On
  240. RewriteCond %{REQUEST_FILENAME} !-f
  241. RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]
  242. Then, create a small script that tells Apache how to spawn your FastCGI
  243. program. Create a file ``mysite.fcgi`` and place it in your Web directory, and
  244. be sure to make it executable:
  245. .. code-block:: python
  246. #!/usr/bin/python
  247. import sys, os
  248. # Add a custom Python path.
  249. sys.path.insert(0, "/home/user/python")
  250. # Switch to the directory of your project. (Optional.)
  251. # os.chdir("/home/user/myproject")
  252. # Set the DJANGO_SETTINGS_MODULE environment variable.
  253. os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings"
  254. from django.core.servers.fastcgi import runfastcgi
  255. runfastcgi(method="threaded", daemonize="false")
  256. Restarting the spawned server
  257. -----------------------------
  258. If you change any Python code on your site, you'll need to tell FastCGI the
  259. code has changed. But there's no need to restart Apache in this case. Rather,
  260. just reupload ``mysite.fcgi``, or edit the file, so that the timestamp on the
  261. file will change. When Apache sees the file has been updated, it will restart
  262. your Django application for you.
  263. If you have access to a command shell on a Unix system, you can accomplish this
  264. easily by using the ``touch`` command::
  265. touch mysite.fcgi
  266. Serving admin media files
  267. =========================
  268. Regardless of the server and configuration you eventually decide to use, you
  269. will also need to give some thought to how to serve the admin media files. The
  270. advice given in the :ref:`mod_wsgi <serving-the-admin-files>` documentation
  271. is also applicable in the setups detailed above.
  272. Forcing the URL prefix to a particular value
  273. ============================================
  274. Because many of these fastcgi-based solutions require rewriting the URL at
  275. some point inside the Web server, the path information that Django sees may not
  276. resemble the original URL that was passed in. This is a problem if the Django
  277. application is being served from under a particular prefix and you want your
  278. URLs from the ``{% url %}`` tag to look like the prefix, rather than the
  279. rewritten version, which might contain, for example, ``mysite.fcgi``.
  280. Django makes a good attempt to work out what the real script name prefix
  281. should be. In particular, if the Web server sets the ``SCRIPT_URL`` (specific
  282. to Apache's mod_rewrite), or ``REDIRECT_URL`` (set by a few servers, including
  283. Apache + mod_rewrite in some situations), Django will work out the original
  284. prefix automatically.
  285. In the cases where Django cannot work out the prefix correctly and where you
  286. want the original value to be used in URLs, you can set the
  287. :setting:`FORCE_SCRIPT_NAME` setting in your main ``settings`` file. This sets the
  288. script name uniformly for every URL served via that settings file. Thus you'll
  289. need to use different settings files if you want different sets of URLs to
  290. have different script names in this case, but that is a rare situation.
  291. As an example of how to use it, if your Django configuration is serving all of
  292. the URLs under ``'/'`` and you wanted to use this setting, you would set
  293. ``FORCE_SCRIPT_NAME = ''`` in your settings file.