nginx + php (fastCGI) 설치
환경 : centos 5.x (32bit)
우리가 사용하는 서버의 대 다수는 아파치 웹서버가 주로 사용하고 있다
이미지 전용서버를 찾던 중 nginx를 알게되어 실제 어느정도 퍼포먼스가 나오는지
알고 싶어 설치 및 테스트를 해 보았으나
그렇게 체감속도가 빠른것은 아니였으나 이미지로딩이나 cpu부하는 전반적으로
apache 서버보다 더 성능이 우수하게 나왔다
그럼 설치에 앞서 구성을 살펴보면
nginx + php + memcache + eaccelerator + ImageMagick + imagick
자료 다운로드
[root@xinet ~]# wget http://sysoev.ru/nginx/nginx-0.8.46.tar.gz
[root@xinet ~]# wget http://www.php.net/get/php-5.2.14.tar.gz/from/this/mirror
[root@xinet ~]# wget http://php-fpm.org/downloads/php-5.2.14-fpm-0.5.14.diff.gz
[root@xinet ~]# wget http://pecl.php.net/get/memcache-2.2.5.tgz
[root@xinet ~]# wget http://bart.eaccelerator.net/source/0.9.6.1/eaccelerator-0.9.6.1.tar.bz2
[root@xinet ~]# wget http://blog.s135.com/soft/linux/nginx_php/imagick/ImageMagick.tar.gz
[root@xinet ~]# wget http://pecl.php.net/get/imagick-2.3.0.tgz
[root@xinet ~]# wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.13.1.tar.gz
1. 라이브러리 설치하기
기본적으로 라이브러리를 yum 서비를 이용하여 설치한다
하지만 yum으로 설치되지 않는 라이브러리가 있으니 컴파일 하여 설치 (iconv)
[root@xinet ~]# tar xvfz libiconv-1.13.1.tar.gz
[root@xinet ~]# cd libiconv-1.13.1
[root@xinet libiconv-1.13.1]# ./configure && make && make install
2. mysql 설치
mysql은 yum을 이용하거나 직접 컴파일 하여 설치한다 (생략)
3. PHP 설치
PHP설치에 앞서 fastcgi를 사용하기 위해서 패치 작업을 진행한다
[root@xinet ~]# gzip -cd php-5.2.14-fpm-0.5.14.diff.gz | patch -d php-5.2.14 -p1
라이브러리를 참고 할수 있게 환경변수를 추가해 준다
[root@xinet ~]# echo “/usr/lib” >> /etc/ld.so.conf
[root@xinet ~]# echo “/usr/local/lib” >> /etc/ld.so.conf
[root@xinet ~]# echo “/usr/local/mysql/lib/mysql” >> /etc/ld.so.conf
적용
[root@xinet ~]# cd php-5.2.14
[root@xinet php-5.2.14]# ./configure –prefix=/usr/local/php –with-config-file-path=/usr/local/php/etc –with-mysql=/usr/local/mysql –with-mysqli=/usr/local/mysql/bin/mysql_config –with-iconv-dir=/usr/local –with-freetype-dir –with-jpeg-dir –with-png-dir –with-zlib –with-libxml-dir=/usr –enable-xml –disable-rpath –enable-discard-path –enable-safe-mode –enable-bcmath –enable-shmop –enable-sysvsem –enable-inline-optimization –with-curl –with-curlwrappers –enable-mbregex –enable-fastcgi –enable-fpm –enable-force-cgi-redirect –enable-mbstring –with-mcrypt –with-gd –enable-gd-native-ttf –with-openssl –with-mhash –enable-pcntl –enable-sockets –with-ldap –with-ldap-sasl –with-xmlrpc –enable-zip –enable-soap
[root@xinet php-5.2.14]# make ZEND_EXTRA_LIBS=’-liconv’
[root@xinet php-5.2.14]# make install
[root@xinet php-5.2.14]# cp php.ini-dist /usr/local/php/etc/php.ini
php.ini 내용값 변경
[root@xinet php-5.2.14]# perl -pi -e “s/upload_max_filesize = 2M/upload_max_filesize = 12M/g” /usr/local/php/etc/php.ini
[root@xinet php-5.2.14]# perl -pi -e “s/allow_url_fopen = On/allow_url_fopen = Off/g” /usr/local/php/etc/php.ini
4. PHP가속을 위한 memcache 및 imagick 설치 (이미지 썸네일 기능)
[root@xinet ~]# tar zxvf memcache-2.2.5.tgz
[root@xinet ~]# cd memcache-2.2.5/
[root@xinet memcache-2.2.5]# /usr/local/php/bin/phpize
[root@xinet memcache-2.2.5]# ./configure –with-php-config=/usr/local/php/bin/php-config
[root@xinet memcache-2.2.5]# make && make install
[root@xinet memcache-2.2.5]# cd ../
[root@xinet ~]# tar jxvf eaccelerator-0.9.6.1.tar.bz2
[root@xinet ~]# cd eaccelerator-0.9.6.1/
[root@xinet eaccelerator-0.9.6.1]# /usr/local/php/bin/phpize
[root@xinet eaccelerator-0.9.6.1]# ./configure –enable-eaccelerator=shared –with-php-config=/usr/local/php/bin/php-config
[root@xinet eaccelerator-0.9.6.1]# make && make install
[root@xinet eaccelerator-0.9.6.1]# cd ../
ImageMagick + imagick 을 설치하는것은 php에서 image를 썸네일 작업을 하기 위해서 이다
[root@xinet ~]# cd ImageMagick-6.5.1-2/
[root@xinet ImageMagick-6.5.1-2]# ./configure && make && make install
[root@xinet ImageMagick-6.5.1-2]# cd ../
[root@xinet ~]# tar zxvf imagick-2.3.0.tgz
[root@xinet ~]# cd imagick-2.3.0/
[root@xinet imagick-2.3.0]# /usr/local/php/bin/phpize
[root@xinet imagick-2.3.0]# ./configure –with-php-config=/usr/local/php/bin/php-config
[root@xinet imagick-2.3.0]# make && make install
[root@xinet imagick-2.3.0]# cd ../
5. PHP.INI 환경파일에 위에서 등록한 so파일을 등록한다
[root@xinet ~]# sed -i ‘s#output_buffering = Off#output_buffering = On#’ /usr/local/php/etc/php.ini
[root@xinet ~]# sed -i “s#; always_populate_raw_post_data = On#always_populate_raw_post_data = On#g” /usr/local/php/etc/php.ini
[root@xinet ~]# sed -i “s#; cgi.fix_pathinfo=0#cgi.fix_pathinfo=0#g” /usr/local/php/etc/php.ini
직접 수정을 해도 상관이 없다
내용 추가 (추가라기보단 493라인 근처에 내용을 수정 및 추가해 주면 된다)
extension_dir = “/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/”
extension = “memcache.so”
extension = “imagick.so”
변수 값 수정
output_buffering = Off –> output_buffering = On 으로 수정
; cgi.fix_pathinfo=0 —> 주석제거
6. PHP 가속을 위한 eAccelerator 설정
[root@xinet ~]# chown -R nobody:nobody /var/tmp/eaccelerator_cache/
[root@xinet ~]# vi /usr/local/php/etc/php.ini
php.ini 내용 추가
[eaccelerator]
zend_extension=”/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/eaccelerator.so”
eaccelerator.shm_size=”64″
eaccelerator.cache_dir=”/var/tmp/eaccelerator_cache”
eaccelerator.enable=”1″
eaccelerator.optimizer=”1″
eaccelerator.check_mtime=”1″
eaccelerator.debug=”0″
eaccelerator.filter=””
eaccelerator.shm_max=”0″
eaccelerator.shm_ttl=”3600″
eaccelerator.shm_prune_period=”3600″
eaccelerator.shm_only=”0″
eaccelerator.compress=”1″
eaccelerator.compress_level=”9″
PHP 버전 확인
[root@xinet ~]# /usr/local/php/bin/php -v
PHP 5.2.14 (cli) (built: Aug 24 2010 23:36:41)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2010 Zend Technologies
with eAccelerator v0.9.6.1, Copyright (c) 2004-2010 eAccelerator, by eAccelerator
eaccelerator_cache 폴더 권한 변경
[root@xinet ~]# chown -R nobody:nobody /var/tmp/eaccelerator_cache/
7. PHP-FPM 환경파일 수정 및 스크립트 구성
먼저 php-fpm.conf 원본파일을 복사 후 삭제 재 작성
[root@xinet ~]# vi /usr/local/php/etc/php-fpm.conf
<?xml version=”1.0″ ?>
<configuration>
All relative paths in this config are relative to php’s install prefix
<section name=”global_options”>
Pid file
<value name=”pid_file”>/usr/local/php/logs/php-fpm.pid</value>
Error log file
<value name=”error_log”>/usr/local/php/logs/php-fpm.log</value>
Log level
<value name=”log_level”>notice</value>
When this amount of php processes exited with SIGSEGV or SIGBUS …
<value name=”emergency_restart_threshold”>10</value>
… in a less than this interval of time, a graceful restart will be initiated.
Useful to work around accidental curruptions in accelerator’s shared memory.
<value name=”emergency_restart_interval”>1m</value>
Time limit on waiting child’s reaction on signals from master
<value name=”process_control_timeout”>5s</value>
Set to ‘no’ to debug fpm
<value name=”daemonize”>yes</value>
</section>
<workers>
<section name=”pool”>
Name of pool. Used in logs and stats.
<value name=”name”>default</value>
Address to accept fastcgi requests on.
Valid syntax is ‘ip.ad.re.ss:port’ or just ‘port’ or ‘/path/to/unix/socket’
<value name=”listen_address”>127.0.0.1:9000</value>
<value name=”listen_options”>
Set listen(2) backlog
<value name=”backlog”>-1</value>
Set permissions for unix socket, if one used.
In Linux read/write permissions must be set in order to allow connections from web server.
Many BSD-derrived systems allow connections regardless of permissions.
<value name=”owner”></value>
<value name=”group”></value>
<value name=”mode”>0666</value>
</value>
Additional php.ini defines, specific to this pool of workers.
<value name=”php_defines”>
<value name=”sendmail_path”>/usr/sbin/sendmail -t -i</value>
<value name=”display_errors”>0</value>
</value>
Unix user of processes
<value name=”user”>nobody</value>
Unix group of processes
<value name=”group”>nobody</value>
Process manager settings
<value name=”pm”>
Sets style of controling worker process count.
Valid values are ‘static’ and ‘apache-like’
<value name=”style”>static</value>
Sets the limit on the number of simultaneous requests that will be served.
Equivalent to Apache MaxClients directive.
Equivalent to PHP_FCGI_CHILDREN environment in original php.fcgi
Used with any pm_style.
<value name=”max_children”>128</value>
Settings group for ‘apache-like’ pm style
<value name=”apache_like”>
Sets the number of server processes created on startup.
Used only when ‘apache-like’ pm_style is selected
<value name=”StartServers”>20</value>
Sets the desired minimum number of idle server processes.
Used only when ‘apache-like’ pm_style is selected
<value name=”MinSpareServers”>5</value>
Sets the desired maximum number of idle server processes.
Used only when ‘apache-like’ pm_style is selected
<value name=”MaxSpareServers”>35</value>
</value>
</value>
The timeout (in seconds) for serving a single request after which the worker process will be terminated
Should be used when ‘max_execution_time’ ini option does not stop script execution for some reason
‘0s’ means ‘off’
<value name=”request_terminate_timeout”>0s</value>
The timeout (in seconds) for serving of single request after which a php backtrace will be dumped to slow.log file
‘0s’ means ‘off’
<value name=”request_slowlog_timeout”>0s</value>
The log file for slow requests
<value name=”slowlog”>logs/slow.log</value>
Set open file desc rlimit
<value name=”rlimit_files”>65535</value>
Set max core size rlimit
<value name=”rlimit_core”>0</value>
Chroot to this directory at the start, absolute path
<value name=”chroot”></value>
Chdir to this directory at the start, absolute path
<value name=”chdir”></value>
Redirect workers’ stdout and stderr into main error log.
If not set, they will be redirected to /dev/null, according to FastCGI specs
<value name=”catch_workers_output”>yes</value>
How much requests each process should execute before respawn.
Useful to work around memory leaks in 3rd party libraries.
For endless request processing please specify 0
Equivalent to PHP_FCGI_MAX_REQUESTS
<value name=”max_requests”>1024</value>
Comma separated list of ipv4 addresses of FastCGI clients that allowed to connect.
Equivalent to FCGI_WEB_SERVER_ADDRS environment in original php.fcgi (5.2.2+)
Makes sense only with AF_INET listening socket.
<value name=”allowed_clients”>127.0.0.1</value>
Pass environment variables like LD_LIBRARY_PATH
All $VARIABLEs are taken from current environment
<value name=”environment”>
<value name=”HOSTNAME”>$HOSTNAME</value>
<value name=”PATH”>/usr/local/bin:/usr/bin:/bin</value>
<value name=”TMP”>/tmp</value>
<value name=”TMPDIR”>/tmp</value>
<value name=”TEMP”>/tmp</value>
<value name=”OSTYPE”>$OSTYPE</value>
<value name=”MACHTYPE”>$MACHTYPE</value>
<value name=”MALLOC_CHECK_”>2</value>
</value>
</section>
</workers>
</configuration>
복사하여 붙혀넣기 하면 간혹 에러 발생 그래서 스크립트 파일 다운로드 할수 있게 링크
6934478037.conf
시작스크립트 심벌릭 링크
[root@xinet ~]# /etc/rc.d/init.d/php-fpm start
Starting php_fpm done
[root@xinet ~]# ps -ef | grep php-cgi
root 5315 1 0 00:34 ? 00:00:00 /usr/local/php/bin/php-cgi –fpm –fpm-config /usr/local/php/etc/php-fpm.conf
nobody 5316 5315 0 00:34 ? 00:00:00 /usr/local/php/bin/php-cgi –fpm –fpm-config /usr/local/php/etc/php-fpm.conf
—생략—–
이렇게까지 하면 php를 설치한것이다 (fastcgi 구성)
8. nginx 설치
[root@xinet ~]# tar xvfz nginx-0.8.46.tar.gz
[root@xinet ~]# cd nginx-0.8.46
nginx에서 사용하는 모듈중에 geoip 부분을 추후 사용하기 위해서 geoip를 설치한다
[root@xinet nginx-0.8.46]# yum -y install GeoIP GeoIP-devel GeoIP-data perl-Geo-IP
[root@xinet nginx-0.8.46]# ./configure –prefix=/usr/local/nginx \
–conf-path=/usr/local/nginx/conf/nginx.conf \
–sbin-path=/usr/local/nginx/sbin/nginx \
–pid-path=/usr/local/nginx/log/nginx.pid \
–lock-path=/usr/local/nginx/log/nginx.lock \
–error-log-path=/usr/local/nginx/log/error.log \
–user=nobody –group=nobody \
–with-http_ssl_module \
–with-http_realip_module \
–with-http_addition_module \
–with-http_image_filter_module \
–with-http_geoip_module \
–with-http_sub_module \
–with-http_dav_module \
–with-http_flv_module \
–with-http_gzip_static_module \
–with-http_random_index_module \
–with-http_secure_link_module \
–with-http_degradation_module \
–with-http_stub_status_module \
–with-http_perl_module \
–with-perl=which perl
\
–with-cpp_test_module \
–with-cpu-opt=pentium4 \
–http-log-path=/usr/local/nginx/log/nginx-access.log \
–http-client-body-temp-path=/usr/local/nginx/tmp/client \
–http-proxy-temp-path=/usr/local/nginx/tmp/proxy \
–http-fastcgi-temp-path=/usr/local/nginx/tmp/fastcgi
[root@xinet nginx-0.8.46]# make && make install
원본 nginx.conf 파일은 보관하고 새로운 파일 작어
[root@xinet nginx-0.8.46]# mv /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf.ori
[root@xinet nginx-0.8.46]# vi /usr/local/nginx/conf/nginx.conf
추가
user nobody nobody;
worker_processes 2;
error_log /usr/local/nginx/log/nginx_error.log crit;
pid /usr/local/nginx/log/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;
events
{
use epoll;
worker_connections 65535;
}
http
{
include mime.types;
default_type application/octet-stream;
#charset gb2312;
server_names_hash_bucket_size 128;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 8m;
sendfile on;
tcp_nopush on;
keepalive_timeout 60;
tcp_nodelay on;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
#limit_zone crawler $binary_remote_addr 10m;
server
{
listen 80;
server_name testnginx.xinet.kr;
index index.html index.htm index.php;
root /free/home/test/html;
#limit_conn crawler 20;
location ~ .*\.(php|php5)?$
{
#fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 1h;
}
log_format access ‘$remote_addr – $remote_user [$time_local] “$request” ‘
‘$status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” $http_x_forwarded_for’;
access_log /usr/local/nginx/log/access.log access;
}
server
{
listen 80;
server_name status.nginx.xinet.kr;
location / {
stub_status on;
access_log off;
}
}
}
nginx 시작 스크립트 구성
[root@xinet nginx-0.8.46]# vi /etc/rc.d/init.d/nginx
#!/bin/sh
#
# nginx – this script starts and stops the nginx daemon
#
# chkconfig: – 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /etc/nginx/nginx.conf
# config: /etc/sysconfig/nginx
# pidfile: /var/run/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ “$NETWORKING” = “no” ] && exit 0
nginx=”/usr/local/nginx/sbin/nginx”
prog=$(basename $nginx)
NGINX_CONF_FILE=”/usr/local/nginx/conf/nginx.conf”
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
make_dirs() {
# make required directories
user=nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -
options=$nginx -V 2>&1 | grep 'configure arguments:'
for opt in $options; do
if [ echo $opt | grep '.*-temp-path'
]; then
value=echo $opt | cut -d "=" -f 2
if [ ! -d “$value” ]; then
# echo “creating” $value
mkdir -p $value && chown -R $user $value
fi
fi
done
}
start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
make_dirs
echo -n $”Starting $prog: “
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $”Stopping $prog: “
killproc $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
configtest || return $?
stop
sleep 1
start
}
reload() {
configtest || return $?
echo -n $”Reloading $prog: “
killproc $nginx -HUP
RETVAL=$?
echo
}
force_reload() {
restart
}
configtest() {
$nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case “$1” in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart|configtest)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
;;
*)
echo $”Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}”
exit 2
esac
스크립트 다운로드 할수 있게 아래 링크 다운
4972584132.xxx
nginx 시작
nginx (을)를 시작 중: [ OK ]
이제 php화면을 뛰어보자
[root@xinet nginx-0.8.46]# useradd test
[root@xinet nginx-0.8.46]# vi /free/home/test/html/index.php
phpinfo();
?>
위와 같이 출력후 웹페이지 출력하면 nginx + php가 구동이 완료되었다
빠진 부분이 있었네. Zend만 이제 설치하면 최종 완료된다…