4

Настройка Debian 6 + PHP 5.4 + PHP-FPM + MySQL + Bitrix

Ниже приведен алгоритм настройки и конфиги #VPS с Debian 6 32bit, 128Мб оперативной памяти и 128Мб свопа для комфортной работы на нем 1C-Битрикс:Стандарт.

Обновление системы и настройка необходимых репозиториев

[shell] apt-get update && apt-get -y upgrade && apt-get -y install mc htop[/shell]

Подключаем репозитории Dotdeb, для того что бы установить PHP5.4 + PHP-FPM:

  1. Добавьте в файл: /etc/apt/sources.list следующие строки:

[code]
deb http://packages.dotdeb.org squeeze all
deb-src http://packages.dotdeb.org squeeze all
[/code]

  1. Для инсталяции PHP 5.4 на Debian 6.0 “Squeeze” нужно добавить строки:

[code]
deb http://packages.dotdeb.org squeeze-php54 all
deb-src http://packages.dotdeb.org squeeze-php54 all
[/code]

    1. Установите ключи доступа к репозиторию GnuPG key

[shell]wget http://www.dotdeb.org/dotdeb.gpg
cat dotdeb.gpg | sudo apt-key add — [/shell]

  1. Обновите систему:
    [shell] # apt-get update && apt-get -y upgrade [/shell]

Устновка и настройка PHP+NGINX+MYSQL

[shell] apt-get -y install mysql-server-5.5 nginx[/shell]
[shell] apt-get -y install php5-fpm php5-gd php5-curl php5-mcrypt php5-json
php5-apc php5-mysql[/shell]

Настройки PHP

/etc/php5/php.ini дописать в конец файла строки:

[code]

;allow_call_time_pass_reference = On ;bitrix-env
max_execution_time = 300 ;bitrix-env
error_reporting = E_ALL & ~E_NOTICE ;bitrix-env
display_errors = On ;bitrix-env
post_max_size = 24M ;bitrix-env
enable_dl = Off ;bitrix-env
upload_max_filesize = 24M ;bitrix-env
;define_syslog_variables = 1 ;bitrix-env
mbstring.func_overload = 2 ;bitrix-env
mbstring.internal_encoding = UTF-8 ;bitrix-env
;extension=geoip.so ;bitrix-env
;extension=xdebug.so ;bitrix-env
;mysql.default_socket = /var/lib/mysqld/mysqld.sock ;bitrix-env
;sendmail_path = msmtp -t -i ;bitrix-env
session.save_path = /temp/sessions/ ;bitrix-env
session.cookie_lifetime = 592000
session.gc_probability = 1
session.gc_divisor = 500
session.gc_maxlifetime = 104800
realpath_cache_size = 4096k ;bitrix-env
max_file_uploads = 100 ;bitrix-env
date.timezone = ‘Europe/Moscow’
;sendmail_path = /usr/lib/sendmail -t -i -f MASTER@DOMAIN.RU
[/code]

Обратите внимание, что нужно создать папку для сессий: /temp/sessions/ — с правами на запись пользователю www-data.

в /etc/php5/mods-available/apc.ini дописать:

[code] extension=apc.so apc.ttl = 30 apc.max_file_size = 4M [/code]

Настройка хоста /etc/php5/pool.d/www.conf сводится к исправлению работы через сокет, на TCP: Меняем:

listen = /var/run/php5-fpm.sock

на

listen = 127.0.0.1:9000

Настройки Mysql

[code]

[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock

[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0

[mysqld]
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
# lc-message-dir is unknown to MySQL 5.1
#lc-messages-dir = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address = 127.0.0.1
#
# * Fine Tuning
#
table_open_cache = 256
key_buffer = 4M
max_allowed_packet = 16M
thread_stack = 192K
thread_cache_size = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover = BACKUP
max_connections = 4
table_cache = 256
#thread_concurrency = 10
#
# * Query Cache Configuration
#
query_cache_limit = 1M
query_cache_size = 2M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file = /var/log/mysql/mysql.log
#general_log = 1
#
# Error logging goes to syslog due to /etc/mysql/conf.d/mysqld_safe_syslog.cnf.
#
# Here you can see queries with especially long duration
#slow_query_log = 1
#slow_query_log_file = /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
# other settings you may need to change.
#server-id = 1
#log_bin = /var/log/mysql/mysql-bin.log
#expire_logs_days = 10
#max_binlog_size = 100M
#binlog_do_db = include_database_name
#binlog_ignore_db = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem

innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
transaction-isolation = READ-COMMITTED
innodb_buffer_pool_size = 32M

[mysqldump]
quick
quote-names
max_allowed_packet = 16M

[mysql]
#no-auto-rehash # faster start of mysql but no tab completition

[isamchk]
key_buffer = 8M
#
# * IMPORTANT: Additional settings that can override those from this file!
# The files must end with ‘.cnf’, otherwise they’ll be ignored.
#

!includedir /etc/mysql/conf.d/

[/code]

Настройки Nginx

/nginx/nginx.conf

[code]
user www-data;

worker_processes 1;

error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
worker_connections 1024;
}

http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main ‘$remote_addr — $remote_user [$time_local] "$request" ‘
‘$status $body_bytes_sent "$http_referer" ‘
‘"$http_user_agent" "$http_x_forwarded_for"’;
access_log /var/log/nginx/access.log main;
## Proxy
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffers 8 16k;
proxy_buffer_size 32k;
## Compression
gzip on;
gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
gzip_disable "MSIE [1-6].(?!.*SV1)";
### TCP options
tcp_nodelay on;
tcp_nopush on;
keepalive_timeout 10;
sendfile on;
# include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}

[/code]

/etc/nginx/sites-enabled/default

[code]

server {
listen 80;
server_name domainname.ru;
root /var/www;
index index.php;
access_log /var/log/nginx/$host-access.log;

autoindex off;
gzip on; # use gzip compression
gzip_proxied any; # enable proxy for the fcgi requests

location / {
try_files $uri $uri/ @bitrix;
}

location ~ \.php$ {
# fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param QUERY_STRING $args;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SERVER_NAME $server_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_USER $remote_user;
fastcgi_intercept_errors on;
fastcgi_ignore_client_abort off;
fastcgi_connect_timeout 60;
fastcgi_send_timeout 180;
fastcgi_read_timeout 180;
fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
}

location @bitrix {
#fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/bitrix/urlrewrite.php;
}

location ~* ^.+\.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpe?g|avi|zip|gz|bz2?|rar|swf)$ {
access_log off;
expires max;
}

location ~ (/\.ht|/bitrix/modules|/upload/support/not_image) {
deny all;
}

location ~ /.svn/ {
deny all;
}

error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

[/code]

    P.S. Статья обновляется.

4 Comments

  1. Замечательно, спасибо 🙂

  2. нашёл в чём проблемма нужно ещё установить

    apt-get -y install php5-mysql

  3. 1. В конфигурации PHP много закомментированных строк, не несущих смысловой нагрузки (хочется верить, что читатели всё-таки не совсем бездумно копипастят конфиги). Может быть, причешете?
    2. Из текста неясно, зачем перевешивать php-fpm с Unix-сокета на TCP. Это имеет смысл только если php-fpm и веб-сервер на разных машинах. Если они на одной, php-fpm лучше вешать на Unix-сокет — нагрузка меньше.
    3. Ни слова о настройке пула процессов FPM. По умолчанию пул статический, это лишняя трата памяти. Лучше использовать ondemand, время жизни по халяве можно выставить 10 секунд, а позже подправить исходя из нагрузки.

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *