Lighttpd - установка, базовая настройка и тестирование производительности

  • user warning: Table './muffsql1/cache_filter' is marked as crashed and should be repaired query: SELECT data, created, headers, expire, serialized FROM cache_filter WHERE cid = '2:606a26d834e97803249b84087998a839' in /usr/local/www/muff.kiev.ua/includes/cache.inc on line 27.
  • user warning: Table './muffsql1/cache_filter' is marked as crashed and should be repaired query: UPDATE cache_filter SET data = '<p class=\"rtecenter\"><img hspace=\"5\" alt=\"Lighttpd\" vspace=\"5\" style=\"width: 151px; height: 144px\" src=\"http://muff.kiev.ua/files/Lighttpd_logo.png\" /></p>\n<p class=\"rtejustify\">Решил на одном из серверов вместо <strong>Apache </strong>установить быстрый и легкий <strong>Lighttpd</strong>. Просмотреть результаты тестирования этих двух web-сервером можно по ссылке: <a href=\"http://www.howtoforge.com/benchmark-apache2-vs-lighttpd-images\"><strong>Lighttpd vs Apache</strong></a>.</p>\n<p class=\"rtejustify\">Итак,&nbsp;результаты тестирования говорят сами за себя,&nbsp;так что &quot;опробовать&quot;&nbsp;<strong>Lighttpd </strong>однозначно стоит.</p>\n<p class=\"rtejustify\">Итак, установку выполним как всегда из портов,&nbsp;благо они обновляются ежедневно по cron-у. Даем команду на установку:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td># <strong>cd /usr/ports/www/lighttpd &amp;&amp; make install clean &amp;&amp; rehash</strong></td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">&nbsp;При сборке были отмечены следующие опции:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<p class=\"rtecenter\"><strong>Options for lighttpd 1.4.28_4</strong></p>\n<pre>\n[X] BZIP2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Enable Bzip2 support\n[X] CML&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Enable Cache Meta Language support\n[X] FAM&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Enable fam/gamin support\n[X] GDBM&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Enable gdbm storage support\n[ ] IPV6&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Enable IPV6 support\n[X] LIBEV&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Enable libev support\n[X] MAGNET&nbsp;&nbsp;&nbsp;&nbsp; Enable magnet support\n[X] MEMCACHE&nbsp;&nbsp; Enable memory caching support\n[X] MYSQL&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Enable MYSQL support\n[X] MYSQLAUTH&nbsp; Enable mysql auth (requires WITH_MYSQL)\n[X] NODELAY&nbsp;&nbsp;&nbsp; Set TCP_NODELAY on listening sockets\n[ ] OPENLDAP&nbsp;&nbsp; Enable LDAP support\n[X] OPENSSL&nbsp;&nbsp;&nbsp; Enable SSL support\n[X] SPAWNFCGI&nbsp; Depend on spawn-fcgi utility \n[ ] VALGRIND&nbsp;&nbsp; Enable valgrind support\n[ ] WEBDAV&nbsp;&nbsp;&nbsp;&nbsp; Enable WebDAV support</pre></td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">Первым делом добавим поддержку <strong>Lighttpd</strong> в <strong>rc.conf</strong>:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<p># <strong>echo \'# Web-server Lighttpd\' &gt;&gt; /etc/rc.conf</strong><br />\n # <strong>echo \'lighttpd_enable=&quot;YES&quot;\' &gt;&gt; /etc/rc.conf</strong></p>\n</td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">Потом приступаем к редактированию конфигурационного файла. В&nbsp;конфигурационный файл по умолчанию (<strong>/usr/local/etc/lighttpd/lighttpd.conf</strong>), внес только единственное изменение - отключил поддержку IPv6. Все остальное оставил по умолчанию - еще будет время для внесения изменений. Пытаемся запустить <strong>Lighttpd</strong>:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<p># <strong>sh /usr/local/etc/rc.d/lighttpd start</strong></p>\n<p>Starting lighttpd.<br />\n 2011-05-07 01:34:45: (configfile.c.1214) base-docroot doesn\'t exist: /usr/local/www/data/<br />\n 2011-05-07 01:34:45: (server.c.620) setting default values failed<br />\n /usr/local/etc/rc.d/lighttpd: WARNING: failed to start lighttpd</p>\n</td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">Хм... Как оказалось,&nbsp;каталога для размещения данных не существует. Необходимо его создать и выставить необходимые права:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<p># <strong>mkdir /usr/local/www/data</strong><br />\n # <strong>chown www:www /usr/local/www/data</strong></p>\n</td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">Ну и для полноты картины,&nbsp;положим&nbsp;туда индексный html-файл:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<p>#&nbsp;<strong>cat /usr/local/www/data/index.html<br />\n </strong>&nbsp;</p>\n<p>&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;<br />\n &quot;<a href=\"http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd\">http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd</a>&quot;&gt;<br />\n &lt;html xmlns=&quot;<a href=\"http://www.w3.org/1999/xhtml\">http://www.w3.org/1999/xhtml</a>&quot; lang=&quot;ru&quot; xml:lang=&quot;ru&quot;&gt;<br />\n &lt;head&gt;<br />\n &nbsp; &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=KOI8-R&quot;&gt;<br />\n &nbsp; &lt;title&gt;Тестовая страница&lt;/title&gt;<br />\n &lt;/head&gt;</p>\n<p>&lt;body&gt;</p>\n<p>&lt;center&gt;&lt;h3&gt;Тестовая страница.&lt;/p&gt;&lt;/center&gt;<br />\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;<br />\n &lt;center&gt;&lt;h3&gt;Test Ok!&lt;/a&gt;&lt;/h3&gt;&lt;/center&gt;<br />\n &lt;p&gt;&amp;nbsp;&lt;/p&gt;</p>\n<p>&lt;/body&gt;<br />\n &lt;/html&gt;</p>\n</td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">Также укажем IP-адрес,&nbsp;на котором &quot;слушать&quot;&nbsp;запросы. &quot;Забиндим&quot; <strong>Lighttpd</strong> на IP 192.168.159.254. Соответственно строка в конфигурационном файле принимает следующий вид:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>$SERVER[&quot;socket&quot;] == &quot;192.168.159.254:80&quot; { }</td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">Снова пытаемся запустить <strong>Lighttpd</strong>:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td># <strong>sh /usr/local/etc/rc.d/lighttpd start<br />\n </strong>Starting lighttpd.</td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">Проверяем,&nbsp;есть ли в процессах <strong>Lighttpd</strong>:</p>\n<p class=\"rtejustify\">\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td># <strong>ps -ax | grep lighttpd<br />\n </strong>&nbsp;7051&nbsp; ??&nbsp; S&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0:00.00 /usr/local/sbin/lighttpd -f /usr/local/etc/lighttpd/lighttpd.conf</td>\n</tr>\n</tbody>\n</table>\n</p>\n<p class=\"rtejustify\"><strong>Lighttpd</strong> в&nbsp;процессах присутствует,&nbsp;что означает,&nbsp;что мы на верном пути. Кстати,&nbsp;стоит обратить внимание на то,&nbsp;что в памяти висит только один процесс,&nbsp;а не несколько,&nbsp;как в случае с <strong>Apache</strong>.</p>\n<p class=\"rtejustify\">Теперь проверим,&nbsp;слушает ли <strong>Lighttpd</strong> запросы на 80 порту, и обрабатывает ли их. Попробуем в браузере ввести IP-адрес сервера. В результате имеем вывод следующей веб-страницы,&nbsp;что подтверждает обработку запросов:</p>\n<p class=\"rtecenter\"><a class=\"thickbox\" title=\"\" href=\"/files/imagepicker/1/Lighttpd-01.png\"><img class=\"imgp_img\" alt=\"Картинки\" src=\"/files/imagepicker/1/thumbs/Lighttpd-01.png\" /></a></p>\n<p class=\"rtecenter\">&nbsp;</p>\n<p class=\"rtecenter\"><span style=\"color: #ff0000\"><strong>Тестирование производительности.</strong></span></p>\n<p class=\"rtejustify\">Теперь попробуем провести самостоятельное тестирование производительности <strong>Lighttpd</strong> и&nbsp; <strong>Apache</strong>. На этой же машине установил <strong>Apache</strong>. Остановим <strong>Lighttpd</strong> и запустим <strong>Apache</strong>. <strong>Apache</strong> запускаем тоже на дефолтных настройках,&nbsp;изменив в конфигурационном файле все вхождения /usr/local/www/apache22/data на значение /usr/local/www/data. Стоит иметь ввиду,&nbsp;что отдаем статический файл <strong>index.html</strong>.</p>\n<p>Добавим в <strong>rc.conf</strong>&nbsp;запуск <strong>Apache</strong>:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td># <strong>echo \'apache22_enable=&quot;YES&quot;\' &gt;&gt; /etc/rc.conf</strong></td>\n</tr>\n</tbody>\n</table>\n<p>Останов <strong>Lighttpd</strong> и запуск <strong>Apache</strong>:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<p># <strong>sh /usr/local/etc/rc.d/lighttpd stop<br />\n </strong>Stopping lighttpd.</p>\n<p># <strong>sh /usr/local/etc/rc.d/apache22 start<br />\n </strong>Performing sanity check on apache22 configuration:<br />\n Syntax OK<br />\n Starting apache22.</p>\n</td>\n</tr>\n</tbody>\n</table>\n<p>Теперь с помощью <strong>ab</strong>&nbsp;(<strong>Apache HTTP server benchmarking tool</strong>) проверим и сравним производительность web-севреров.</p>\n<p class=\"rtecenter\"><u><strong>apache-worker-2.2.17_2</strong></u></p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<pre>\n# <strong>ab -n 1000 </strong><strong>http://192.168.159.254/</strong>\n\nThis is ApacheBench, Version 2.3 &lt;$Revision: 655654 $&gt;\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, <a href=\"http://www.zeustech.net/\">http://www.zeustech.net/</a>\nLicensed to The Apache Software Foundation, <a href=\"http://www.apache.org/\">http://www.apache.org/\n\n</a></pre><pre>\nBenchmarking 195.3.159.254 (be patient)\nCompleted 100 requests\nCompleted 200 requests\nCompleted 300 requests\nCompleted 400 requests\nCompleted 500 requests\nCompleted 600 requests\nCompleted 700 requests\nCompleted 800 requests\nCompleted 900 requests\nCompleted 1000 requests\nFinished 1000 requests\n\n</pre><pre>\nServer Software: Apache/2.2.17\nServer Hostname: 195.3.159.254\nServer Port: 80\n\n</pre><pre>\nDocument Path: /\nDocument Length: 469 bytes\n\n</pre><pre>\nConcurrency Level: 1\nTime taken for tests: 1.451 seconds\nComplete requests: 1000\nFailed requests: 0\nWrite errors: 0\nTotal transferred: 760000 bytes\nHTML transferred: 469000 bytes\nRequests per second: <span style=\"color: #ff0000\">689.24</span> [#/sec] (mean)\nTime per request: 1.451 [ms] (mean)\nTime per request: 1.451 [ms] (mean, across all concurrent requests)\nTransfer rate: 511.55 [Kbytes/sec] received\n\n</pre><pre>\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 1 0.1 1 2\nProcessing: 1 1 0.2 1 5\nWaiting: 1 1 0.2 1 5\nTotal: 1 1 0.2 1 5\n\n</pre><pre>\nPercentage of the requests served within a certain time (ms)\n 50% 1\n 66% 1\n 75% 1\n 80% 1\n 90% 2\n 95% 2\n 98% 2\n 99% 2\n 100% 5 (longest request)</pre></td>\n</tr>\n</tbody>\n</table>\n<p><span style=\"color: #0000ff\"><strong>Производительность</strong></span>: 689.24 запросов в секунду.</p>\n<p>Останавливаем <strong>Apache</strong> и запускаем <strong>Lighttpd</strong>:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<p># <strong>sh /usr/local/etc/rc.d/apache22 stop<br />\n </strong>Stopping apache22.<br />\n Waiting for PIDS: 7658.</p>\n<p># <strong>sh /usr/local/etc/rc.d/lighttpd start<br />\n </strong>Starting lighttpd.</p>\n</td>\n</tr>\n</tbody>\n</table>\n<p>Теперь протестируем производительность <strong>Lighttpd</strong>.</p>\n<p class=\"rtecenter\"><u><strong>lighttpd-1.4.28_4</strong></u></p>\n<p><table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<p># <strong>ab -n 1000 </strong><strong>http://192.168.159.254/</strong></p>\n<pre>\nThis is ApacheBench, Version 2.3 &lt;$Revision: 655654 $&gt;\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, <a href=\"http://www.zeustech.net/\">http://www.zeustech.net/</a>\nLicensed to The Apache Software Foundation, <a href=\"http://www.apache.org/\">http://www.apache.org/</a>\n\nBenchmarking 195.3.159.254 (be patient)\nCompleted 100 requests\nCompleted 200 requests\nCompleted 300 requests\nCompleted 400 requests\nCompleted 500 requests\nCompleted 600 requests\nCompleted 700 requests\nCompleted 800 requests\nCompleted 900 requests\nCompleted 1000 requests\nFinished 1000 requests</pre><pre>\nServer Software: lighttpd\nServer Hostname: 195.3.159.254\nServer Port: 80\n\nDocument Path: /\nDocument Length: 469 bytes</pre><pre>\nConcurrency Level: 1\nTime taken for tests: 1.294 seconds\nComplete requests: 1000\nFailed requests: 0\nWrite errors: 0\nTotal transferred: 696000 bytes\nHTML transferred: 469000 bytes\nRequests per second: <span style=\"color: #ff0000\">772.86</span> [#/sec] (mean)\nTime per request: 1.294 [ms] (mean)\nTime per request: 1.294 [ms] (mean, across all concurrent requests)\nTransfer rate: 525.31 [Kbytes/sec] received\n\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 1 0.1 1 2\nProcessing: 1 1 0.1 1 2\nWaiting: 0 1 0.1 1 2\nTotal: 1 1 0.2 1 3</pre><pre>\nPercentage of the requests served within a certain time (ms)\n 50% 1\n 66% 1\n 75% 1\n 80% 1\n 90% 1\n 95% 1\n 98% 2\n 99% 2\n 100% 3 (longest request)</pre></td>\n</tr>\n</tbody>\n</table>\n</p>\n<p class=\"rtejustify\">Хм... Если чесно, то я ожидал большего... Попробуем теперь &quot;прикрутить&quot; <strong>PHP</strong> к <strong>Lighttpd</strong> (ну и к Apache заодно). Для начала установим PHP. Опции сборки установил такие:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<p class=\"rtecenter\"><strong>Options for php52 5.2.17</strong></p>\n<pre>\n[X] CLI Build CLI version\n[X] CGI Build CGI version\n[X] APACHE&nbsp;&nbsp;&nbsp;&nbsp; Build Apache module\n[ ] DEBUG&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Enable debug\n[X] SUHOSIN&nbsp;&nbsp;&nbsp; Enable Suhosin protection system (not for jails)\n[X] MULTIBYTE&nbsp; Enable zend multibyte support\n[ ] IPV6&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Enable ipv6 support\n[ ] MAILHEAD&nbsp;&nbsp; Enable mail header patch\n[ ] REDIRECT&nbsp;&nbsp; Enable force-cgi-redirect support (CGI only)\n[ ] DISCARD&nbsp;&nbsp;&nbsp; Enable discard-path support (CGI only)\n[X] FASTCGI&nbsp;&nbsp;&nbsp; Enable fastcgi support (CGI only)\n[X] FPM&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Enable fastcgi process manager (CGI only)\n[X] PATHINFO&nbsp;&nbsp; Enable path-info-check support (CGI only)</pre></td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">Для <strong>Apache</strong> необходимо добавить в конфигурационный файл такие строки в блок <strong>&lt;IfModule mime_module&gt;</strong>:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>AddType application/x-httpd-php .php<br />\n AddType application/x-httpd-php-source .phps</td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">Параметр <strong>DirectoryIndex</strong> необходимо видоизменить до следующего значения:</p>\n<p class=\"rtejustify\">\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>DirectoryIndex index.php</td>\n</tr>\n</tbody>\n</table>\n</p>\n<p class=\"rtejustify\">Ну&nbsp;и создадим конфигурационный файл для PHP, воспользовавшись одним из предложенных примеров:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td><span class=\"Apple-style-span\" style=\"widows: 2; text-transform: none; text-indent: 0px; border-collapse: separate; font: medium \'Times New Roman\'; white-space: normal; orphans: 2; letter-spacing: normal; color: rgb(0,0,0); word-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px\"><span class=\"Apple-style-span\" style=\"line-height: 16px; border-collapse: collapse; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; -webkit-border-horizontal-spacing: 1px; -webkit-border-vertical-spacing: 1px\"># </span><strong><span class=\"Apple-style-span\" style=\"line-height: 16px; border-collapse: collapse; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; -webkit-border-horizontal-spacing: 1px; -webkit-border-vertical-spacing: 1px\">cp /usr/local/etc/php.ini-production /usr/local/etc/php.ini</span></strong></span></td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">Теперь&nbsp;поместим в<strong> /usr/local/www/data</strong> файл <strong>index.php</strong> следующего содержания:</p>\n<p class=\"rtejustify\">\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<div><span class=\"Apple-style-span\" style=\"widows: 2; text-transform: none; text-indent: 0px; border-collapse: separate; font: medium \'Times New Roman\'; white-space: normal; orphans: 2; letter-spacing: normal; color: rgb(0,0,0); word-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px\"><span class=\"Apple-style-span\" style=\"line-height: 16px; border-collapse: collapse; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; -webkit-border-horizontal-spacing: 1px; -webkit-border-vertical-spacing: 1px\"># </span><strong><span class=\"Apple-style-span\" style=\"line-height: 16px; border-collapse: collapse; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; -webkit-border-horizontal-spacing: 1px; -webkit-border-vertical-spacing: 1px\">cat /usr/local/www/data/index.php</span></strong></span></div>\n<p><span class=\"Apple-style-span\" style=\"widows: 2; text-transform: none; text-indent: 0px; border-collapse: separate; font: medium \'Times New Roman\'; white-space: normal; orphans: 2; letter-spacing: normal; color: rgb(0,0,0); word-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px\"><span class=\"Apple-style-span\" style=\"line-height: 16px; border-collapse: collapse; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; -webkit-border-horizontal-spacing: 1px; -webkit-border-vertical-spacing: 1px\">&lt;?php</span></span><br />\n <span class=\"Apple-style-span\" style=\"widows: 2; text-transform: none; text-indent: 0px; border-collapse: separate; font: medium \'Times New Roman\'; white-space: normal; orphans: 2; letter-spacing: normal; color: rgb(0,0,0); word-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px\"><span class=\"Apple-style-span\" style=\"line-height: 16px; border-collapse: collapse; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; -webkit-border-horizontal-spacing: 1px; -webkit-border-vertical-spacing: 1px\">&nbsp;&nbsp;&nbsp; phpinfo();</span></span><br />\n <span class=\"Apple-style-span\" style=\"widows: 2; text-transform: none; text-indent: 0px; border-collapse: separate; font: medium \'Times New Roman\'; white-space: normal; orphans: 2; letter-spacing: normal; color: rgb(0,0,0); word-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px\"><span class=\"Apple-style-span\" style=\"line-height: 16px; border-collapse: collapse; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; -webkit-border-horizontal-spacing: 1px; -webkit-border-vertical-spacing: 1px\">?&gt;</span></span></p>\n</td>\n</tr>\n</tbody>\n</table>\n</p>\n<p class=\"rtejustify\">Теперь попробуем &quot;подружить&quot; <strong>Lighttpd</strong> и <strong>PHP</strong>. Связка&nbsp; <strong>Lighttpd</strong> и <strong>PHP</strong> будет работать через <strong>FastCGI</strong>, поэтому необходимо, чтобы в <strong>php.ini</strong> переменная <strong>cgi.fix_pathinfo</strong> была установлена в значение <strong>1</strong> (по умолчанию).</p>\n<p class=\"rtejustify\">Следующий шаг - правка конфигурационных файлов <strong>Lighttpd</strong>. В файле <strong>/usr/local/etc/lighttpd/modules.conf</strong> необходимо расскоментировать такую строку:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>include &quot;conf.d/fastcgi.conf&quot;</td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">А в файл /usr/local/etc/lighttpd/conf.d/fastcgi.conf необходимо вставить такой блок:</p>\n<p class=\"rtejustify\">\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>fastcgi.server = ( &quot;.php&quot; =&gt; ((<br />\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;bin-path&quot; =&gt; &quot;/usr/local/bin/php-cgi&quot;,<br />\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;socket&quot; =&gt; &quot;/tmp/php.socket&quot;,<br />\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;max-procs&quot; =&gt; &quot;2&quot;,<br />\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;bin-environment&quot; =&gt; (<br />\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;PHP_FCGI_CHILDREN&quot; =&gt; &quot;16&quot;,<br />\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;PHP_FCGI_MAX_REQUESTS&quot; =&gt; &quot;10000&quot;<br />\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ),<br />\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;bin-copy-environment&quot; =&gt; (<br />\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;PATH&quot;, &quot;SHELL&quot;, &quot;USER&quot;<br />\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ),<br />\n &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;broken-scriptfilename&quot; =&gt; &quot;enable&quot;<br />\n )))</td>\n</tr>\n</tbody>\n</table>\n</p>\n<p class=\"rtejustify\">После этого перезаускаем <strong>Lighttpd</strong>, чтобы изменения вступили в силу:</p>\n<p class=\"rtejustify\">\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td><span class=\"Apple-style-span\" style=\"widows: 2; text-transform: none; text-indent: 0px; border-collapse: separate; font: medium \'Times New Roman\'; white-space: normal; orphans: 2; letter-spacing: normal; color: rgb(0,0,0); word-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px\"><span class=\"Apple-style-span\" style=\"line-height: 16px; border-collapse: collapse; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; -webkit-border-horizontal-spacing: 1px; -webkit-border-vertical-spacing: 1px\"># </span><strong><span class=\"Apple-style-span\" style=\"line-height: 16px; border-collapse: collapse; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; -webkit-border-horizontal-spacing: 1px; -webkit-border-vertical-spacing: 1px\">sh /usr/local/etc/rc.d/lighttpd restart</span></strong></span></td>\n</tr>\n</tbody>\n</table>\n</p>\n<p class=\"rtejustify\">В&nbsp;результате должна отображаться страница свойств <strong>PHP</strong> (как при использовании <strong>Apache</strong>, так и при использовании <strong>Lighttpd</strong>:</p>\n<p class=\"rtecenter\"><a class=\"thickbox\" title=\"\" href=\"/files/imagepicker/1/Lighttpd-02.png\"><img class=\"imgp_img\" alt=\"Картинки\" src=\"/files/imagepicker/1/thumbs/Lighttpd-02.png\" /></a></p>\n<p class=\"rtejustify\">Не буду уже описывать остановы и запуски определенных серверов... Итак, тестируем <strong>Apache</strong> на вивод PHP-содержимого.</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<div># <strong>ab -n 1000 </strong><strong>http://192.168.159.254/</strong></div>\n<pre>\nThis is ApacheBench, Version 2.3 &lt;$Revision: 655654 $&gt;\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, <a href=\"http://www.zeustech.net/\">http://www.zeustech.net/</a>\nLicensed to The Apache Software Foundation, <a href=\"http://www.apache.org/\">http://www.apache.org/</a>\n\n</pre><pre>\nBenchmarking 192.168.159.254 (be patient)\nCompleted 100 requests\nCompleted 200 requests\nCompleted 300 requests\nCompleted 400 requests\nCompleted 500 requests\nCompleted 600 requests\nCompleted 700 requests\nCompleted 800 requests\nCompleted 900 requests\nCompleted 1000 requests\nFinished 1000 requests\n\n</pre><pre>\nServer Software: Apache/2.2.17\nServer Hostname: 192.168.159.254\nServer Port: 80\n\n</pre><pre>\nDocument Path: /\nDocument Length: 27895 bytes\n\n</pre><pre>\nConcurrency Level: 1\nTime taken for tests: 1.097 seconds\nComplete requests: 1000\nFailed requests: 989\n (Connect: 0, Receive: 0, Length: 989, Exceptions: 0)\nWrite errors: 0\nNon-2xx responses: 989\nTotal transferred: 776381 bytes\nHTML transferred: 506623 bytes\nRequests per second: <span style=\"color: #ff0000\">911.48</span> [#/sec] (mean)\nTime per request: 1.097 [ms] (mean)\nTime per request: 1.097 [ms] (mean, across all concurrent requests)\nTransfer rate: 691.07 [Kbytes/sec] received\n\n</pre><pre>\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 0 0.1 0 1\nProcessing: 1 1 0.5 1 11\nWaiting: 0 1 0.4 1 11\nTotal: 1 1 0.5 1 11\n\n</pre><pre>\nPercentage of the requests served within a certain time (ms)\n 50% 1\n 66% 1\n 75% 1\n 80% 1\n 90% 1\n 95% 1\n 98% 2\n 99% 4\n 100% 11 (longest request)</pre></td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">А&nbsp;теперь проверим производительность PHP на <strong>Lighttpd</strong>:</p>\n<table border=\"1\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n<tbody>\n<tr>\n<td>\n<div># <strong>ab -n 1000 </strong><strong>http://192.168.159.254/</strong></div>\n<pre>\nThis is ApacheBench, Version 2.3 &lt;$Revision: 655654 $&gt;\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, <a href=\"http://www.zeustech.net/\">http://www.zeustech.net/</a>\nLicensed to The Apache Software Foundation, <a href=\"http://www.apache.org/\">http://www.apache.org/</a>\n\n</pre><pre>\nBenchmarking 192.168.159.254 (be patient)\nCompleted 100 requests\nCompleted 200 requests\nCompleted 300 requests\nCompleted 400 requests\nCompleted 500 requests\nCompleted 600 requests\nCompleted 700 requests\nCompleted 800 requests\nCompleted 900 requests\nCompleted 1000 requests\nFinished 1000 requests\n\n</pre><pre>\nServer Software: lighttpd\nServer Hostname: 192.168.159.254\nServer Port: 80\n\n</pre><pre>\nDocument Path: /\nDocument Length: 23106 bytes\n\n</pre><pre>\nConcurrency Level: 1\nTime taken for tests: 3.873 seconds\nComplete requests: 1000\nFailed requests: 0\nWrite errors: 0\nTotal transferred: 23250000 bytes\nHTML transferred: 23106000 bytes\nRequests per second: <span style=\"color: #ff0000\">258.20</span> [#/sec] (mean)\nTime per request: 3.873 [ms] (mean)\nTime per request: 3.873 [ms] (mean, across all concurrent requests)\nTransfer rate: 5862.47 [Kbytes/sec] received\n\n</pre><pre>\nConnection Times (ms)\n min mean[+/-sd] median max\nConnect: 0 0 0.1 0 1\nProcessing: 3 3 0.2 3 5\nWaiting: 1 1 0.2 1 3\nTotal: 3 4 0.2 4 5\n\n</pre><pre>\nPercentage of the requests served within a certain time (ms)\n 50% 4\n 66% 4\n 75% 4\n 80% 4\n 90% 4\n 95% 4\n 98% 5\n 99% 5\n 100% 5 (longest request)</pre></td>\n</tr>\n</tbody>\n</table>\n<p class=\"rtejustify\">При выводе динамического содержимого <strong>Lighttpd</strong> сильно уступает в производительности <strong>Apache</strong>. Однако это может быть следствием того, что в <strong>Lighttpd</strong> PHP&nbsp;работает через <strong>FastCGI</strong>. Проверять эту теорию нету ни времени ни желания.</p>\n<p class=\"rtejustify\">Остановимся на том,&nbsp;что Apache желательно использовать при выдаче динамического содержимого, а <strong>Lighttpd</strong> желательно использовать для выдачи статического контента.</p>\n', created = 1767408896, expire = 1767495296, headers = '', serialized = 0 WHERE cid = '2:606a26d834e97803249b84087998a839' in /usr/local/www/muff.kiev.ua/includes/cache.inc on line 112.
  • user warning: Table './muffsql1/cache_filter' is marked as crashed and should be repaired query: SELECT data, created, headers, expire, serialized FROM cache_filter WHERE cid = '2:07243fc0252056071eaa62af8c18d662' in /usr/local/www/muff.kiev.ua/includes/cache.inc on line 27.
  • user warning: Table './muffsql1/cache_filter' is marked as crashed and should be repaired query: UPDATE cache_filter SET data = '<p class=\"rtecenter\"><a class=\"thickbox\" href=\"/files/imagepicker/1/wake_up_ua.png\"><img alt=\"Вставай, Україно!\" class=\"imgp_img\" src=\"/files/imagepicker/1/thumbs/wake_up_ua.png\" style=\"height:200px; width:150px\" /></a></p>\n', created = 1767408896, expire = 1767495296, headers = '', serialized = 0 WHERE cid = '2:07243fc0252056071eaa62af8c18d662' in /usr/local/www/muff.kiev.ua/includes/cache.inc on line 112.
  • user warning: Table './muffsql1/cache_filter' is marked as crashed and should be repaired query: SELECT data, created, headers, expire, serialized FROM cache_filter WHERE cid = '3:cc913d232116f0426090404133377d88' in /usr/local/www/muff.kiev.ua/includes/cache.inc on line 27.
  • user warning: Table './muffsql1/cache_filter' is marked as crashed and should be repaired query: SELECT data, created, headers, expire, serialized FROM cache_filter WHERE cid = '2:d9a86123bfcbc57878743027b584400b' in /usr/local/www/muff.kiev.ua/includes/cache.inc on line 27.
  • user warning: Table './muffsql1/cache_filter' is marked as crashed and should be repaired query: UPDATE cache_filter SET data = '<p class=\"rtecenter\"><a href=\"http://muff.kiev.ua/rss.xml\"><img alt=\"RSS\" width=\"160\" height=\"60\" src=\"http://muff.kiev.ua/files/muf-rss.png\" /></a></p>\n', created = 1767408896, expire = 1767495296, headers = '', serialized = 0 WHERE cid = '2:d9a86123bfcbc57878743027b584400b' in /usr/local/www/muff.kiev.ua/includes/cache.inc on line 112.
  • user warning: Table './muffsql1/cache_filter' is marked as crashed and should be repaired query: SELECT data, created, headers, expire, serialized FROM cache_filter WHERE cid = '3:39649256b636e3d5ded656bc52bd8c01' in /usr/local/www/muff.kiev.ua/includes/cache.inc on line 27.
Версия для печатиОтправить другуPDF version

Lighttpd

Решил на одном из серверов вместо Apache установить быстрый и легкий Lighttpd. Просмотреть результаты тестирования этих двух web-сервером можно по ссылке: Lighttpd vs Apache.

Итак, результаты тестирования говорят сами за себя, так что "опробовать" Lighttpd однозначно стоит.

Итак, установку выполним как всегда из портов, благо они обновляются ежедневно по cron-у. Даем команду на установку:

# cd /usr/ports/www/lighttpd && make install clean && rehash

 При сборке были отмечены следующие опции:

Options for lighttpd 1.4.28_4

[X] BZIP2      Enable Bzip2 support
[X] CML        Enable Cache Meta Language support
[X] FAM        Enable fam/gamin support
[X] GDBM       Enable gdbm storage support
[ ] IPV6       Enable IPV6 support
[X] LIBEV      Enable libev support
[X] MAGNET     Enable magnet support
[X] MEMCACHE   Enable memory caching support
[X] MYSQL      Enable MYSQL support
[X] MYSQLAUTH  Enable mysql auth (requires WITH_MYSQL)
[X] NODELAY    Set TCP_NODELAY on listening sockets
[ ] OPENLDAP   Enable LDAP support
[X] OPENSSL    Enable SSL support
[X] SPAWNFCGI  Depend on spawn-fcgi utility 
[ ] VALGRIND   Enable valgrind support
[ ] WEBDAV     Enable WebDAV support

Первым делом добавим поддержку Lighttpd в rc.conf:

# echo '# Web-server Lighttpd' >> /etc/rc.conf
# echo 'lighttpd_enable="YES"' >> /etc/rc.conf

Потом приступаем к редактированию конфигурационного файла. В конфигурационный файл по умолчанию (/usr/local/etc/lighttpd/lighttpd.conf), внес только единственное изменение - отключил поддержку IPv6. Все остальное оставил по умолчанию - еще будет время для внесения изменений. Пытаемся запустить Lighttpd:

# sh /usr/local/etc/rc.d/lighttpd start

Starting lighttpd.
2011-05-07 01:34:45: (configfile.c.1214) base-docroot doesn't exist: /usr/local/www/data/
2011-05-07 01:34:45: (server.c.620) setting default values failed
/usr/local/etc/rc.d/lighttpd: WARNING: failed to start lighttpd

Хм... Как оказалось, каталога для размещения данных не существует. Необходимо его создать и выставить необходимые права:

# mkdir /usr/local/www/data
# chown www:www /usr/local/www/data

Ну и для полноты картины, положим туда индексный html-файл:

cat /usr/local/www/data/index.html
 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ru" xml:lang="ru">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=KOI8-R">
  <title>Тестовая страница</title>
</head>

<body>

<center><h3>Тестовая страница.</p></center>
<p>&nbsp;</p>
<center><h3>Test Ok!</a></h3></center>
<p>&nbsp;</p>

</body>
</html>

Также укажем IP-адрес, на котором "слушать" запросы. "Забиндим" Lighttpd на IP 192.168.159.254. Соответственно строка в конфигурационном файле принимает следующий вид:

$SERVER["socket"] == "192.168.159.254:80" { }

Снова пытаемся запустить Lighttpd:

# sh /usr/local/etc/rc.d/lighttpd start
Starting lighttpd.

Проверяем, есть ли в процессах Lighttpd:

# ps -ax | grep lighttpd
 7051  ??  S      0:00.00 /usr/local/sbin/lighttpd -f /usr/local/etc/lighttpd/lighttpd.conf

Lighttpd в процессах присутствует, что означает, что мы на верном пути. Кстати, стоит обратить внимание на то, что в памяти висит только один процесс, а не несколько, как в случае с Apache.

Теперь проверим, слушает ли Lighttpd запросы на 80 порту, и обрабатывает ли их. Попробуем в браузере ввести IP-адрес сервера. В результате имеем вывод следующей веб-страницы, что подтверждает обработку запросов:

Картинки

 

Тестирование производительности.

Теперь попробуем провести самостоятельное тестирование производительности Lighttpd и  Apache. На этой же машине установил Apache. Остановим Lighttpd и запустим Apache. Apache запускаем тоже на дефолтных настройках, изменив в конфигурационном файле все вхождения /usr/local/www/apache22/data на значение /usr/local/www/data. Стоит иметь ввиду, что отдаем статический файл index.html.

Добавим в rc.conf запуск Apache:

# echo 'apache22_enable="YES"' >> /etc/rc.conf

Останов Lighttpd и запуск Apache:

# sh /usr/local/etc/rc.d/lighttpd stop
Stopping lighttpd.

# sh /usr/local/etc/rc.d/apache22 start
Performing sanity check on apache22 configuration:
Syntax OK
Starting apache22.

Теперь с помощью ab (Apache HTTP server benchmarking tool) проверим и сравним производительность web-севреров.

apache-worker-2.2.17_2

# ab -n 1000 http://192.168.159.254/

This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 195.3.159.254 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests

Server Software:        Apache/2.2.17
Server Hostname:        195.3.159.254
Server Port:            80

Document Path:          /
Document Length:        469 bytes

Concurrency Level:      1
Time taken for tests:   1.451 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      760000 bytes
HTML transferred:       469000 bytes
Requests per second:    689.24 [#/sec] (mean)
Time per request:       1.451 [ms] (mean)
Time per request:       1.451 [ms] (mean, across all concurrent requests)
Transfer rate:          511.55 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    1   0.1      1       2
Processing:     1    1   0.2      1       5
Waiting:        1    1   0.2      1       5
Total:          1    1   0.2      1       5

Percentage of the requests served within a certain time (ms)
  50%      1
  66%      1
  75%      1
  80%      1
  90%      2
  95%      2
  98%      2
  99%      2
 100%      5 (longest request)

Производительность: 689.24 запросов в секунду.

Останавливаем Apache и запускаем Lighttpd:

# sh /usr/local/etc/rc.d/apache22 stop
Stopping apache22.
Waiting for PIDS: 7658.

# sh /usr/local/etc/rc.d/lighttpd start
Starting lighttpd.

Теперь протестируем производительность Lighttpd.

lighttpd-1.4.28_4

# ab -n 1000 http://192.168.159.254/

This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 195.3.159.254 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests
Server Software:        lighttpd
Server Hostname:        195.3.159.254
Server Port:            80

Document Path:          /
Document Length:        469 bytes
Concurrency Level:      1
Time taken for tests:   1.294 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      696000 bytes
HTML transferred:       469000 bytes
Requests per second:    772.86 [#/sec] (mean)
Time per request:       1.294 [ms] (mean)
Time per request:       1.294 [ms] (mean, across all concurrent requests)
Transfer rate:          525.31 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    1   0.1      1       2
Processing:     1    1   0.1      1       2
Waiting:        0    1   0.1      1       2
Total:          1    1   0.2      1       3
Percentage of the requests served within a certain time (ms)
  50%      1
  66%      1
  75%      1
  80%      1
  90%      1
  95%      1
  98%      2
  99%      2
 100%      3 (longest request)

Хм... Если чесно, то я ожидал большего... Попробуем теперь "прикрутить" PHP к Lighttpd (ну и к Apache заодно). Для начала установим PHP. Опции сборки установил такие:

Options for php52 5.2.17

[X] CLI        Build CLI version
[X] CGI        Build CGI version
[X] APACHE     Build Apache module
[ ] DEBUG      Enable debug
[X] SUHOSIN    Enable Suhosin protection system (not for jails)
[X] MULTIBYTE  Enable zend multibyte support
[ ] IPV6       Enable ipv6 support
[ ] MAILHEAD   Enable mail header patch
[ ] REDIRECT   Enable force-cgi-redirect support (CGI only)
[ ] DISCARD    Enable discard-path support (CGI only)
[X] FASTCGI    Enable fastcgi support (CGI only)
[X] FPM        Enable fastcgi process manager (CGI only)
[X] PATHINFO   Enable path-info-check support (CGI only)

Для Apache необходимо добавить в конфигурационный файл такие строки в блок <IfModule mime_module>:

AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps

Параметр DirectoryIndex необходимо видоизменить до следующего значения:

DirectoryIndex index.php

Ну и создадим конфигурационный файл для PHP, воспользовавшись одним из предложенных примеров:

# cp /usr/local/etc/php.ini-production /usr/local/etc/php.ini

Теперь поместим в /usr/local/www/data файл index.php следующего содержания:

# cat /usr/local/www/data/index.php

<?php
    phpinfo();
?>

Теперь попробуем "подружить" Lighttpd и PHP. Связка  Lighttpd и PHP будет работать через FastCGI, поэтому необходимо, чтобы в php.ini переменная cgi.fix_pathinfo была установлена в значение 1 (по умолчанию).

Следующий шаг - правка конфигурационных файлов Lighttpd. В файле /usr/local/etc/lighttpd/modules.conf необходимо расскоментировать такую строку:

include "conf.d/fastcgi.conf"

А в файл /usr/local/etc/lighttpd/conf.d/fastcgi.conf необходимо вставить такой блок:

fastcgi.server = ( ".php" => ((
                "bin-path" => "/usr/local/bin/php-cgi",
                "socket" => "/tmp/php.socket",
                "max-procs" => "2",
                "bin-environment" => (
                "PHP_FCGI_CHILDREN" => "16",
                "PHP_FCGI_MAX_REQUESTS" => "10000"
         ),
                "bin-copy-environment" => (
                "PATH", "SHELL", "USER"
        ),
                "broken-scriptfilename" => "enable"
)))

После этого перезаускаем Lighttpd, чтобы изменения вступили в силу:

# sh /usr/local/etc/rc.d/lighttpd restart

В результате должна отображаться страница свойств PHP (как при использовании Apache, так и при использовании Lighttpd:

Картинки

Не буду уже описывать остановы и запуски определенных серверов... Итак, тестируем Apache на вивод PHP-содержимого.

# ab -n 1000 http://192.168.159.254/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.159.254 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests

Server Software:        Apache/2.2.17
Server Hostname:        192.168.159.254
Server Port:            80

Document Path:          /
Document Length:        27895 bytes

Concurrency Level:      1
Time taken for tests:   1.097 seconds
Complete requests:      1000
Failed requests:        989
   (Connect: 0, Receive: 0, Length: 989, Exceptions: 0)
Write errors:           0
Non-2xx responses:      989
Total transferred:      776381 bytes
HTML transferred:       506623 bytes
Requests per second:    911.48 [#/sec] (mean)
Time per request:       1.097 [ms] (mean)
Time per request:       1.097 [ms] (mean, across all concurrent requests)
Transfer rate:          691.07 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       1
Processing:     1    1   0.5      1      11
Waiting:        0    1   0.4      1      11
Total:          1    1   0.5      1      11

Percentage of the requests served within a certain time (ms)
  50%      1
  66%      1
  75%      1
  80%      1
  90%      1
  95%      1
  98%      2
  99%      4
 100%     11 (longest request)

А теперь проверим производительность PHP на Lighttpd:

# ab -n 1000 http://192.168.159.254/
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.159.254 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests

Server Software:        lighttpd
Server Hostname:        192.168.159.254
Server Port:            80

Document Path:          /
Document Length:        23106 bytes

Concurrency Level:      1
Time taken for tests:   3.873 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      23250000 bytes
HTML transferred:       23106000 bytes
Requests per second:    258.20 [#/sec] (mean)
Time per request:       3.873 [ms] (mean)
Time per request:       3.873 [ms] (mean, across all concurrent requests)
Transfer rate:          5862.47 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       1
Processing:     3    3   0.2      3       5
Waiting:        1    1   0.2      1       3
Total:          3    4   0.2      4       5

Percentage of the requests served within a certain time (ms)
  50%      4
  66%      4
  75%      4
  80%      4
  90%      4
  95%      4
  98%      5
  99%      5
 100%      5 (longest request)

При выводе динамического содержимого Lighttpd сильно уступает в производительности Apache. Однако это может быть следствием того, что в Lighttpd PHP работает через FastCGI. Проверять эту теорию нету ни времени ни желания.

Остановимся на том, что Apache желательно использовать при выдаче динамического содержимого, а Lighttpd желательно использовать для выдачи статического контента.

Ваша оценка: Нет Средняя: 3.7 (6 голосов)

Вставай, Україно!

Литература

Наутpо: - Влейте в pот загpузочную кpужку пива...