2011年2月10日木曜日

さくらVPSでLighttpd+PHP+MySQLの高速軽量サーバを作る


以前、さくらVPSで一日6万PVを処理するためにしたことを書かせていただいたのですが


DBが必要になり、以前のApache構成ではメモリとパフォーマンスに不安があったので軽量WebサーバのLighttpd(ライティ)を使ってみました。


LighttpdとPHPを使う場合は、PHPをCGIモードでインストールする必要があります。


Apache+PHPで構成されるサーバは基本的にモジュール版で動いている物が殆どですが、Lighttpdの場合はPHPモジュールがないためWebサーバ(Lighttpd)とPHPを別に動かす必要があります。


PHPを動かすためにfastcgiを使ってPHPのプロセスを管理します。


Lighttpdでは標準でfastcgiをサポートしていますので設定さえすればすぐにPHPが利用できます。



さくらVPSのコントロールパネルからすること


コントロールパネルからrootでログインしユーザを作る

作業用のユーザを作ります



adduser hogehoge


passwd hogehoge





サーバの細かい設定


SSHからhogehogeでログインする

先ほど作ったユーザをwheelに入れます



su -


usermod -aG wheel hogehoge


id hogehoge



wheelグループ以外rootに昇格できないようにします。


必ず一般ユーザをwheelに追加してからこの作業を行ってください。


rootになれなくなります。


vi /etc/pam.d/su



auth required pam_wheel.so use_uid


#コメントアウトを外す



よく使う&必要なライブラリーインストール


yum install bzip2-devel libjpeg libpng libjpeg-devel libpng-devel pcre pcre-devel bzip2 libxml2-devel



全てY



ライブラリーのパスを追加します


vi /etc/ld.so.conf



include ld.so.conf.d/*.conf


/usr/lib


/usr/local/lib


/usr/lib64


/usr/local/lib64



ldconfig




作業用ディレクトリ作成を作っておきます。


今後、ダウンロードや解凍作業などはこのディレクトリで行います。


mkdir /usr/local/work



インストール


cd /usr/local/work



MySQLダウンロード

mysql-5.5.9-linux2.6-x86_64.tar.gz


http://dev.mysql.com/downloads/mirror.php?id=401187#mirrors



MySQLのインストール

MySQLユーザの追加。


MySQLインストール作業はマニュアル通りになります。



adduser mysql -s /sbin/nologin


tar -zxvf mysql-5.5.9-linux2.6-x86_64.tar.gz -C /usr/local/


cd /usr/local/


ln -s /usr/local/mysql-5.5.8-linux2.6-x86_64 /usr/local/mysql


chown root: mysql-5.5.9-linux2.6-x86_64


cd mysql


chown -R mysql .


chgrp -R mysql .


mv data var


scripts/mysql_install_db --user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/var


chown -R root .


chown -R mysql var


cp support-files/my-large.cnf /etc/my.cnf


cp bin/mysql /usr/local/bin/


cp /usr/local/mysql/support-files/mysql.server /etc/rc.d/init.d/mysql




設定ファイル編集


vi /etc/my.cnf



[client]


#password = your_password


port = 3306


socket = /tmp/mysql.sock



[mysqld]


port = 3306


socket = /tmp/mysql.sock


skip-external-locking


key_buffer_size = 256M


max_allowed_packet = 1M


table_open_cache = 256


sort_buffer_size = 1M


read_buffer_size = 1M


read_rnd_buffer_size = 4M


myisam_sort_buffer_size = 64M


thread_cache_size = 8


query_cache_size= 16M


thread_concurrency =


max_connections = 300


#skip-networking


#log-bin=mysql-bin


#binlog_format=mixed


server-id = 1


#server-id = 2


#master-host = <hostname>


#master-user = <username>


#master-password = <password>


#master-port = <port>


#log-bin=mysql-bin


#innodb_data_home_dir = /usr/local/mysql/data


innodb_data_file_path = ibdata1:512M:autoextend


#innodb_log_group_home_dir = /usr/local/mysql/data


innodb_buffer_pool_size = 256M


#innodb_additional_mem_pool_size = 20M


#innodb_log_file_size = 64M


#innodb_log_buffer_size = 8M


#innodb_flush_log_at_trx_commit = 1


#innodb_lock_wait_timeout = 50


[mysqldump]


quick


max_allowed_packet = 16M


[mysql]


no-auto-rehash


#safe-updates


[myisamchk]


key_buffer_size = 128M


sort_buffer_size = 128M


read_buffer = 2M


write_buffer = 2M


[mysqlhotcopy]


interactive-timeout




起動スクリプト編集

vi /etc/init.d/mysql


46行目辺り



basedir=/usr/local/mysql


datadir=/usr/local/mysql/var




起動します。(少し時間がかかります。)


service mysql start



MySQLにログイン


パスワードはまだ設定していないので空白でログインできます。



mysql -uroot -p




パスワードなしユーザを消してrootにパスワードを付ける



SET PASSWORD FOR [email protected]=PASSWORD('パスワード');


drop database test;


delete from mysql.user where user='';


delete from mysql.user where password='';


select user,host,password from mysql.user;




Lighttpd


今回のメインのLighttpdのインストールです。


インストール



wget http://download.lighttpd.net/lighttpd/releases-1.4.x/lighttpd-1.4.28.tar.gz


tar -zxvf lighttpd-1.4.28.tar.gz


cd lighttpd-1.4.28


./configure --disable-ipv6 --without-proxy --without-rrdtool --without-secdownload --without-trigger_b4_dl --without-webdav


make


make install




設定ファイルなどをコピーします。



cp ./doc/initscripts/rc.lighttpd.redhat /etc/init.d/lighttpd


ln -s /usr/local/sbin/lighttpd /usr/sbin/lighttpd


mkdir /etc/lighttpd


cp -r ./doc/config/* /etc/lighttpd/




Lighttpd実行ユーザを追加します。



adduser lighttpd -s /sbin/nologin




Lighttpdが必要とするディレクトリを作ります。



mkdir /var/log/lighttpd


mkdir -p /srv/www/cgi-bin


mkdir /srv/www/htdocs


mkdir -p /var/lib/lighttpd/sockets/


chown lighttpd:lighttpd /var/log/lighttpd


chown -R lighttpd:lighttpd /srv/www


chown -R lighttpd:lighttpd /var/lib/lighttpd/




Lighttpdの設定

server.tagのコメントアウトを外して、server.max-worker=10を追記しました。


server.max-workerはLighttpdの最大起動数です。


Apacheのmpmに該当しますが、アクセス数に応じて設定する必要があります。


さくらVPSの場合は10~30(100万PV/Day~300万PV/Day)ぐらいです。


vi /etc/lighttpd/lighttpd.conf



#######################################################################


##


## /etc/lighttpd/lighttpd.conf


##


## check /etc/lighttpd/conf.d/*.conf for the configuration of modules.


##


#######################################################################


#######################################################################


##


## Some Variable definition which will make chrooting easier.


##


## if you add a variable here. Add the corresponding variable in the


## chroot example aswell.


##


var.log_root = "/var/log/lighttpd"


var.server_root = "/srv/www"


var.state_dir = "/var/run"


var.home_dir = "/var/lib/lighttpd"


var.conf_dir = "/etc/lighttpd"



server.max-worker=10



##


## run the server chrooted.


##


## This requires root permissions during startup.


##


## If you run Chrooted set the the variables to directories relative to


## the chroot dir.


##


## example chroot configuration:


##


#var.log_root = "/logs"


#var.server_root = "/"


#var.state_dir = "/run"


#var.home_dir = "/lib/lighttpd"


#var.vhosts_dir = "/vhosts"


#var.conf_dir = "/etc"


#


#server.chroot = "/srv/www"


##


## Some additional variables to make the configuration easier


##


##


## Base directory for all virtual hosts


##


## used in:


## conf.d/evhost.conf


## conf.d/simple_vhost.conf


## vhosts.d/vhosts.template


##


var.vhosts_dir = server_root + "/vhosts"


##


## Cache for mod_compress


##


## used in:


## conf.d/compress.conf


##


var.cache_dir = "/var/cache/lighttpd"


##


## Base directory for sockets.


##


## used in:


## conf.d/fastcgi.conf


## conf.d/scgi.conf


##


var.socket_dir = home_dir + "/sockets"


##


#######################################################################


#######################################################################


##


## Load the modules.


include "modules.conf"


##


#######################################################################


#######################################################################


##


## Basic Configuration


## ---------------------


##


server.port = 80


##


## Use IPv6?


##


#server.use-ipv6 = "enable"


##


## bind to a specific IP


##


#server.bind = "localhost"


##


## Run as a different username/groupname.


## This requires root permissions during startup.


##


server.username = "lighttpd"


server.groupname = "lighttpd"


##


## enable core files.


##


#server.core-files = "disable"


##


## Document root


##


server.document-root = server_root + "/htdocs"


##


## The value for the "Server:" response field.


##


## It would be nice to keep it at "lighttpd".


##


server.tag = "lighttpd"


##


## store a pid file


##


server.pid-file = state_dir + "/lighttpd.pid"


##


#######################################################################


#######################################################################


##


## Logging Options


## ------------------


##


## all logging options can be overwritten per vhost.


##


## Path to the error log file


##


server.errorlog = log_root + "/error.log"


##


## If you want to log to syslog you have to unset the


## server.errorlog setting and uncomment the next line.


##


#server.errorlog-use-syslog = "enable"


##


## Access log config


##


include "conf.d/access_log.conf"


##


## The debug options are moved into their own file.


## see conf.d/debug.conf for various options for request debugging.


##


include "conf.d/debug.conf"


##


#######################################################################


#######################################################################


##


## Tuning/Performance


## --------------------


##


## corresponding documentation:


## http://www.lighttpd.net/documentation/performance.html


##


## set the event-handler (read the performance section in the manual)


##


## possible options on linux are:


##


## select


## poll


## linux-sysepoll


##


## linux-sysepoll is recommended on kernel 2.6.


##


server.event-handler = "linux-sysepoll"


##


## The basic network interface for all platforms at the syscalls read()


## and write(). Every modern OS provides its own syscall to help network


## servers transfer files as fast as possible


##


## linux-sendfile - is recommended for small files.


## writev - is recommended for sending many large files


##


server.network-backend = "linux-sendfile"


##


## As lighttpd is a single-threaded server, its main resource limit is


## the number of file descriptors, which is set to 1024 by default (on


## most systems).


##


## If you are running a high-traffic site you might want to increase this


## limit by setting server.max-fds.


##


## Changing this setting requires root permissions on startup. see


## server.username/server.groupname.


##


## By default lighttpd would not change the operation system default.


## But setting it to 2048 is a better default for busy servers.


##


server.max-fds = 2048


##


## Stat() call caching.


##


## lighttpd can utilize FAM/Gamin to cache stat call.


##


## possible values are:


## disable, simple or fam.


##


server.stat-cache-engine = "simple"


##


## Fine tuning for the request handling


##


## max-connections == max-fds/2 (maybe /3)


## means the other file handles are used for fastcgi/files


##


server.max-connections = 1024


##


## How many seconds to keep a keep-alive connection open,


## until we consider it idle.


##


## Default: 5


##


#server.max-keep-alive-idle = 5


##


## How many keep-alive requests until closing the connection.


##


## Default: 16


##


#server.max-keep-alive-requests = 16


##


## Maximum size of a request in kilobytes.


## By default it is unlimited (0).


##


## Uploads to your server cant be larger than this value.


##


#server.max-request-size = 0


##


## Time to read from a socket before we consider it idle.


##


## Default: 60


##


#server.max-read-idle = 60


##


## Time to write to a socket before we consider it idle.


##


## Default: 360


##


#server.max-write-idle = 360


##


## Traffic Shaping


## -----------------


##


## see /usr/share/doc/lighttpd/traffic-shaping.txt


##


## Values are in kilobyte per second.


##


## Keep in mind that a limit below 32kB/s might actually limit the


## traffic to 32kB/s. This is caused by the size of the TCP send


## buffer.


##


## per server:


##


#server.kbytes-per-second = 128


##


## per connection:


##


#connection.kbytes-per-second = 32


##


#######################################################################


#######################################################################


##


## Filename/File handling


## ------------------------


##


## files to check for if .../ is requested


## index-file.names = ( "index.php", "index.rb", "index.html",


## "index.htm", "default.htm" )


##


index-file.names += (


"index.xhtml", "index.html", "index.htm", "default.htm", "index.php"


)


##


## deny access the file-extensions


##


## ~ is for backupfiles from vi, emacs, joe, ...


## .inc is often used for code includes which should in general not be part


## of the document-root


url.access-deny = ( "~", ".inc" )


##


## disable range requests for pdf files


## workaround for a bug in the Acrobat Reader plugin.


##


$HTTP["url"] =~ "\.pdf$" {


server.range-requests = "disable"


}


##


## url handling modules (rewrite, redirect)


##


#url.rewrite = ( "^/$" => "/server-status" )


#url.redirect = ( "^/wishlist/(.+)" => "http://www.example.com/$1" )


##


## both rewrite/redirect support back reference to regex conditional using %n


##


#$HTTP["host"] =~ "^www\.(.*)" {


# url.redirect = ( "^/(.*)" => "http://%1/$1" )


#}


##


## which extensions should not be handle via static-file transfer


##


## .php, .pl, .fcgi are most often handled by mod_fastcgi or mod_cgi


##


static-file.exclude-extensions = ( ".php", ".pl", ".fcgi", ".scgi" )


##


## error-handler for status 404


##


#server.error-handler-404 = "/error-handler.html"


#server.error-handler-404 = "/error-handler.php"


##


## Format: <errorfile-prefix><status-code>.html


## -> ..../status-404.html for 'File not found'


##


#server.errorfile-prefix = "/srv/www/htdocs/errors/status-"


##


## mimetype mapping


##


include "conf.d/mime.conf"


##


## directory listing configuration


##


include "conf.d/dirlisting.conf"


##


## Should lighttpd follow symlinks?


##


server.follow-symlink = "enable"


##


## force all filenames to be lowercase?


##


#server.force-lowercase-filenames = "disable"


##


## defaults to /var/tmp as we assume it is a local harddisk


##


server.upload-dirs = ( "/var/tmp" )


##


#######################################################################



#######################################################################


##


## SSL Support


## -------------


##


## To enable SSL for the whole server you have to provide a valid


## certificate and have to enable the SSL engine.::


##


## ssl.engine = "enable"


## ssl.pemfile = "/path/to/server.pem"


##


## The HTTPS protocol does not allow you to use name-based virtual


## hosting with SSL. If you want to run multiple SSL servers with


## one lighttpd instance you must use IP-based virtual hosting: ::


##


## $SERVER["socket"] == "10.0.0.1:443" {


## ssl.engine = "enable"


## ssl.pemfile = "/etc/ssl/private/www.example.com.pem"


## server.name = "www.example.com"


##


## server.document-root = "/srv/www/vhosts/example.com/www/"


## }


##


## If you have a .crt and a .key file, cat them together into a


## single PEM file:


## $ cat /etc/ssl/private/lighttpd.key /etc/ssl/certs/lighttpd.crt \


## > /etc/ssl/private/lighttpd.pem


##


#ssl.pemfile = "/etc/ssl/private/lighttpd.pem"


##


## optionally pass the CA certificate here.


##


##


#ssl.ca-file = ""


##


#######################################################################




fastcgiモジュールの設定

PHPを使う場合はfastcgiのコメントアウトを外す必要があります。


vi /etc/lighttpd/modules.conf



include "conf.d/fastcgi.conf"




fastcgi本体の設定

PHPの起動数を設定します。


PHP_FCGI_CHILDREN * max-procsが最大起動します。


以下の設定ファイルの値で100万PV/Day~300万PV/Dayぐらいを処理できます。



vi /etc/lighttpd/conf.d/fastcgi.conf



server.modules += ( "mod_fastcgi" )


fastcgi.server = ( ".php" =>


( "php-local" =>


(


"socket" => socket_dir + "/php-fastcgi-1.socket",


"bin-path" => server_root + "/cgi-bin/php5",


"max-procs" => 150,


"broken-scriptfilename" => "enable",


)


),


( "php-tcp" =>


(


"host" => "127.0.0.1",


"port" => 9999,


"check-local" => "disable",


"broken-scriptfilename" => "enable",


)


),


( "php-num-procs" =>


(


"socket" => socket_dir + "/php-fastcgi-2.socket",


"bin-path" => server_root + "/cgi-bin/php5",


"bin-environment" => (


"PHP_FCGI_CHILDREN" => "3",


"PHP_FCGI_MAX_REQUESTS" => "10000",


),


"min-procs" => 1,


"max-procs" => 2,


"max-load-per-proc" => 50,


"idle-timeout" => 360,


"broken-scriptfilename" => "enable",


)


),


)





PHPダウンロード

http://php.net/downloads.php



PHPのインストール


tar -zxvf php-5.2.17.tar.gz


cd php-5.2.17


PHP5.3以上の場合は‘--enable-fastcgi’を指定する必要はない




'./configure' \


'--enable-zend-multibyte' \


'--with-zlib' \


'--with-xmlrpc' \


'--with-gd' \


'--with-jpeg-dir=/usr/local' \


'--with-png-dir=/usr/local' \


'--enable-mbstring' \


'--enable-fastcgi' \


'--with-pdo-mysql=/usr/local/mysql' \



make


make test


make install




リンクを張ります。



ln -s /usr/local/bin/php-cgi /srv/www/cgi-bin/php5


ln -s /usr/local/lib/php/extensions/no-debug-non-zts-20060613/ /usr/local/lib/extensions


ln -s /usr/local/lib/php/extensions/no-debug-non-zts-20060613/apc.so /usr/local/lib/


cp php.ini-recommended /usr/local/lib/php.ini


ln -s /usr/local/lib/php.ini /etc/



APCインストール

パフォーマンスをあげるためにAPCもインストールしておきます



pecl install APC


デフォルトでenter




ログローテート


現在の状態では無限にLogが溜まっていくのでログローテートなどで適宜ログを削除していく必要があります。


Apacheのlogrotate時にApacheが停止する問題のログローテートを利用します。


vim /etc/logrotate.d/lighttpd



/var/log/lighttpd/*log {


rotate 14


daily


missingok


sharedscripts


postrotate


for max in $(seq 1 5)


do


LHTTPD_P=`pgrep lighttpd | wc -l`


if [ "$LHTTPD_P" != 0 ]


then


`/usr/bin/pkill lighttpd` > /dev/null


sleep 5s


elif [ "$LHTTPD_P" = 0 ]


then


/etc/init.d/lighttpd start > /dev/null


break


fi


done


LHTTPD_P=`pgrep lighttpd | wc -l`


if [ "$HTTPD_P" = 0 ]


then


echo Can Not Run HTTPD | mail -s HTTPD ALERT メールアドレス


fi


endscript


}







0 件のコメント:

コメントを投稿