ngin+php-fpm делаем веб-сервер под высокую нагрузку

Поиграемся с нагрузкой?
Для сборки делаем
echo “dev-lang/php cgi fpm force-cgi-redirect” >> /etc/portage/package.use/php
echo “www-servers/nginx fastcgi” >> /etc/portage/package.use/nginx

Устанавливаем связку
emerge -avN nginx php mysql

Пробуем запустить

/etc/init.d/nginx start
/etc/init.d/php-fpm start

Проверяем
union kenny # ps aux|grep php
root 1135 0.0 0.1 51824 3520 ? Ss 14:01 0:00 php-fpm: master process (/etc/php/fpm-php5.3/php-fpm.conf)
nobody 1137 0.0 0.0 51820 2884 ? S 14:01 0:00 php-fpm: pool www
nobody 1138 0.0 0.0 51820 2888 ? S 14:01 0:00 php-fpm: pool www
nobody 1139 0.0 0.0 51820 2888 ? S 14:01 0:00 php-fpm: pool www
nobody 1140 0.0 0.0 51820 2888 ? S 14:01 0:00 php-fpm: pool www
nobody 1141 0.0 0.0 51820 2888 ? S 14:01 0:00 php-fpm: pool www
nobody 1142 0.0 0.0 51820 2888 ? S 14:01 0:00 php-fpm: pool www
nobody 1143 0.0 0.0 51820 2888 ? S 14:01 0:00 php-fpm: pool www
nobody 1144 0.0 0.0 51820 2888 ? S 14:01 0:00 php-fpm: pool www
nobody 1145 0.0 0.0 51820 2888 ? S 14:01 0:00 php-fpm: pool www
nobody 1146 0.0 0.0 51820 2888 ? S 14:01 0:00 php-fpm: pool www
nobody 1147 0.0 0.0 51820 2892 ? S 14:01 0:00 php-fpm: pool www
nobody 1148 0.0 0.0 51820 2892 ? S 14:01 0:00 php-fpm: pool www
nobody 1149 0.0 0.0 51820 3020 ? S 14:01 0:00 php-fpm: pool www
nobody 1150 0.0 0.0 51820 3020 ? S 14:01 0:00 php-fpm: pool www
nobody 1151 0.0 0.0 51820 3020 ? S 14:01 0:00 php-fpm: pool www
nobody 1152 0.0 0.0 51820 3020 ? S 14:01 0:00 php-fpm: pool www
nobody 1153 0.0 0.0 51820 3020 ? S 14:01 0:00 php-fpm: pool www
nobody 1154 0.0 0.0 51820 3020 ? S 14:01 0:00 php-fpm: pool www
nobody 1155 0.0 0.0 51820 3020 ? S 14:01 0:00 php-fpm: pool www
nobody 1156 0.0 0.0 51820 3020 ? S 14:01 0:00 php-fpm: pool www
root 1556 0.0 0.0 4084 656 pts/2 S+ 14:05 0:00 grep --colour=auto php
union kenny # ps aux|grep nginx
root 1085 0.0 0.0 4812 640 ? Ss 14:01 0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx 1086 0.0 0.0 4956 960 ? S 14:01 0:00 nginx: worker process
root 1558 0.0 0.0 4084 660 pts/2 S+ 14:05 0:00 grep --colour=auto nginx
union kenny #

Устанавливаем базу

union kenny # /usr/bin/mysql_install_db
Installing MySQL system tables…
OK
Filling help tables…
OK
Далее пробуем запустить mysql
union kenny # /etc/init.d/mysql start

Проверяем

union kenny # ps aux|grep mysql
mysql 1518 0.0 0.7 128156 24148 ? Ssl 14:02 0:00 /usr/sbin/mysqld --defaults-file=/etc/mysql/my.cnf --basedir=/usr --datadir=/var/lib/mysql --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock
root 1561 0.0 0.0 4080 660 pts/2 S+ 14:06 0:00 grep --colour=auto mysql

Вроде все запущено, пробуем зайти через браузер

Начнем конфигурировать

php
Внесём небольшое изменение в основной файл

union kenny # nano /etc/php/fpm-php5.3/php-fpm.conf

;;;;;;;;;;;;;;;;;;;;;
; FPM Configuration ;
;;;;;;;;;;;;;;;;;;;;;
;include=/etc/php/fpm-php5.3/fpm.d/*.conf

;;;;;;;;;;;;;;;;;;
; Global Options ;
;;;;;;;;;;;;;;;;;;

[global]
pid = /var/run/php-fpm.pid
error_log = /var/log/php-fpm.log
log_level = notice
emergency_restart_threshold = 0
emergency_restart_interval = 1m
process_control_timeout = 5s
daemonize = yes

;;;;;;;;;;;;;;;;;;;;
; Pool Definitions ;
;;;;;;;;;;;;;;;;;;;;
[test]
listen = /tmp/default.socket
listen.backlog = -1
user = nginx
group = nginx
listen.mode = 0666
pm = dynamic
pm.max_children = 25
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 4096
request_terminate_timeout = 500s
request_slowlog_timeout = 10s
slowlog = /var/log/php-slow.log
rlimit_files = 4096
rlimit_core = 0
catch_workers_output = yes
env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp
env[OSTYPE] = $OSTYPE
env[MACHTYPE] = $MACHTYPE
env[MALLOC_CHECK_] = 2

приступим к правки конфигурационного файла nginx

Что меняем сразу?
_ worker_processes 1;_ выставляем по количеству процессоров
На тестовой машинки их два.
Далее добавляем следующее
worker_rlimit_nofile 8192; # ограничиваем количество фалов
worker_priority -5;# задаём более высокий приоритет
В секции events
Выставим worker_connections если сервер мощный то можно и побольше для тестового я выставил 16384, такого значения хватит за глаза :slight_smile:
Секция _ http _
У меня она выглядит так
include /etc/nginx/mime.types;
default_type application/octet-stream;

log_format main
'$remote_addr - $remote_user [$time_local] ’
'"$request" $status $bytes_sent ’
'"$http_referer" “$http_user_agent” ’
‘"$gzip_ratio"’;

limit_req_zone $binary_remote_addr zone=limit:16m rate=5r/s;
limit_req_zone $binary_remote_addr zone=limit_def:16m rate=1r/s;
limit_zone one $binary_remote_addr 10m;
fastcgi_cache_valid 200 301 302 304 1m;
fastcgi_cache_key “$request_method|$http_if_modified_since|$http_if_none_match|$host|$request_uri”;
reset_timedout_connection on;
open_file_cache off;
fastcgi_intercept_errors on;
gzip on;
gzip_vary on;
gzip_min_length 1470;
gzip_comp_level 7;
gzip_http_version 1.0;
gzip_proxied any;
gzip_disable “msie6”;
gzip_buffers 4 8k;
gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

output_buffers 1 32k;
postpone_output 1460;

sendfile on;
tcp_nopush on;
tcp_nodelay on;

keepalive_timeout 75 20;

ignore_invalid_headers on;

index index.html;
Секция server

Опишем первый виртуальный хост

limit_conn one 10;
listen 127.0.0.1:80;
server_name 127.0.0.1;

access_log /var/www/localhost/test/log/access.log main;
error_log /var/www/localhost/test/log/error.log error;
root /var/www/localhost/test;

location / {
index index index.html index.htm index.php;
}

location ~ \.php$ {
limit_conn one 10;

try_files $uri =404;
proxy_read_timeout 120;
fastcgi_pass unix://tmp/default.socket;
fastcgi_index index.php;
include fastcgi_params;
}
location /log {
deny all;
}

location /files {
deny all;
}
location ~* ^.+\.(jpg|jpeg|gif|png|js|css|ico)$ {
access_log off;

expires 30d;
add_header Cache-Control public;
}
location ~ /\.ht {
deny all;
}
}

Полный конфиг
user nginx nginx;
worker_processes 2;
worker_rlimit_nofile 8192;
worker_priority -5;

error_log /var/log/nginx/error_log info;

events {
worker_connections 1024;
use epoll;
}

http {
include /etc/nginx/mime.types;
default_type application/octet-stream;

log_format main
'$remote_addr - $remote_user [$time_local] ’
'"$request" $status $bytes_sent ’
'"$http_referer" “$http_user_agent” ’
‘"$gzip_ratio"’;

limit_req_zone $binary_remote_addr zone=limit:16m rate=5r/s;
limit_req_zone $binary_remote_addr zone=limit_def:16m rate=1r/s;
limit_zone one $binary_remote_addr 10m;
fastcgi_cache_valid 200 301 302 304 1m;
fastcgi_cache_key “$request_method|$http_if_modified_since|$http_if_none_match|$host|$request_uri”;
reset_timedout_connection on;
open_file_cache off;
fastcgi_intercept_errors on;
gzip on;
gzip_vary on;
gzip_min_length 1470;
gzip_comp_level 7;
gzip_http_version 1.0;
gzip_proxied any;
gzip_disable “msie6”;
gzip_buffers 4 8k;
gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

output_buffers 1 32k;
postpone_output 1460;

sendfile on;
tcp_nopush on;
tcp_nodelay on;

keepalive_timeout 75 20;

ignore_invalid_headers on;

index index.html;

server {

limit_conn one 10;
listen 127.0.0.1:80;
server_name 127.0.0.1;

access_log /var/www/localhost/test/log/access.log main;
error_log /var/www/localhost/test/log/error.log error;
root /var/www/localhost/test;

location / {
index index index.html index.htm index.php;
}

location ~ \.php$ {
limit_conn one 10;

try_files $uri =404;
proxy_read_timeout 120;
fastcgi_pass unix://tmp/default.socket;
fastcgi_index index.php;
include fastcgi_params;
}
location /log {
deny all;
}

location /files {
deny all;
}
location ~* ^.+\.(jpg|jpeg|gif|png|js|css|ico)$ {
access_log off;

expires 30d;
add_header Cache-Control public;
}
location ~ /\.ht {
deny all;
}
}

}

Созаем папку для нашего сайта
mkdir /var/www/localhost/test

Не забудем про права
chown -R nginx:nginx /var/www
Проверяем работу
union kenny # echo “<?phpinfo();?>” > /var/www/localhost/test/index.php

Перезапускаем связку
/etc/init.d/nginx restart
/etc/init.d/php-fpm restart
в браузере по адресу http://127.0.0.1
и наблюдаем информацию о php
Собственно настройки закончены. Это первая часть остальное будет чуть позже.
Могу сказать одно что такая конфигурация выдержит нагрузку 20К пользователей в сутки.
В планах выложить конфигурацию Mysql, и прочие вкусности.

Решил поднять веб сервер по этой инструкции
при запуске NGINX ругается

|nginx: [emerg] unknown directive “limit_zone” in /etc/nginx/nginx.conf:25

на строчку

limit_zone one $binary_remote_addr 10m;

куда копать ?

в доку nginx:
http://nginx.org/ru/docs/http/ngx_http_limit_conn_module.html