Instalando PHP-FPM com Apache

Submitted by Eric on ter, 03/27/2018 - 17:36
Imagem
PHP FPM

Muitas pessoas preferem utilizar o nginx, mas para o Magento não faz diferença já que o processo PHP é o grande vilão e não conteúdo estático.


Logo após a instalação do Magento temos uma grande quantidade de arquivos PHP:

find . -type f -name "*.php" | wc -l

Total 8.112.

Algumas razões para utilizar o PHP-FPM com Apache:

  • Você quer a performance e flexibilidade do FPM;
  • Você quer executar o PHP como o usuário que é dono do código (não o Apache) para evitar problemas de permissão;
  • Você precisa utilizar arquivos .htaccess;
  • Você prefere a suportabilidade e experiência com o Apache e não quer utilizar o nginx.

Vamos agora à instalação, o tutorial foi feito com o RHEL/CentOS, mas pode ser alterado para qualquer distro.

Instalando o FPM:
 

yum install php-fpm

Por padrão você terá o FPM rodando como apache e configurado no arquivo /etc/php-fpm.d/www.conf.
Talvez seja necessário configurar vários arquivos por domínio e usuário para não ter problemas de permissão.
Vamos configurar o pool do FPM para executar pelo socket ao invéz de TCP pela porta 9000.
Também configure o usuário e permissão para o socket, normalmente o mesmo que o usuário sFTP.

Execute os comandos abaixo:

cd /etc/php-fpm.d
cp www.conf usuario.conf 
mv www.conf www.conf.disabled 
vim usuario.conf

Faça às seguintes alterações:

;listen = 127.0.0.1:9000
listen = /dev/shm/usuario-php.sock

listen.owner = usuario
listen.group = apache
listen.mode = 0660

user = usuario

pm.max_children = 100
pm.start_servers = 35
pm.min_spare_servers = 35

php_admin_value[error_log] = /var/log/php/dominio.com-error.log
php_admin_flag[log_errors] = on
php_admin_value[memory_limit] = 512M

Instalando mod_fastcgi:

Precisamos instalar o fastcgi para comunicar com o FPM, não há muitas packages disponíveis, então temos a opção de compilar ou utilizar uma versão feita pela Nexcess onde foi corrigido um but do Magento com CGI onde duplica headers causando um erro 500:
… aborted: error parsing headers: duplicate header ‘Content-Type’

Vamos utilizar o rpm da Nexcess para fazer a instalação, execute os comandos abaixo:

yum -y install httpd-devel rpm-build -y
mkdir -p /~/fastcgi
cd /~/fastcgi
wget http://pubfiles.nexcess.net/misc/mod_fastcgi-2.4.6-3.el6.src.rpm
rpmbuild --rebuild mod_fastcgi-2.4.6-3.el6.src.rpm
rpm -ivh /~/rpmbuild/RPMS/x86_64/mod_fastcgi-2.4.6-3.el6.x86_64.rpm
rm -f /etc/httpd/conf.d/mod_fastcgi.conf

Configurando o mod_fastcgi:
Crie o arquivo /etc/httpd/conf.d/mod_fastcgi.conf com o conteúdo abaixo. Altere onde está escrito usuario para o usuario que você configurou para executar o código. Para múltiplos pools, adicione mais directivas FastCGIExternalServer.

LoadModule fastcgi_module modules/mod_fastcgi.so
<IfModule mod_fastcgi.c>
Alias /php5.fcgi /var/www/php5.fcgi

FastCGIExternalServer /var/www/php5.fcgi -socket /dev/shm/someuser-php.sock -flush -idle-timeout 1800

AddType application/x-httpd-fastphp5 .php
Action application/x-httpd-fastphp5 /php5.fcgi
</IfModule>

Desativando mod_php:
Execute o seguinte comando para desativar o mod_php:

mv /etc/httpd/conf.d/php.conf /etc/httpd/conf.d/php.disabled
echo "# mod_php disabled, using mod_fastcgi with PHP-FPM instead" >> /etc/httpd/conf.d/php.conf

PHP-FPM é muito bom com o uso de memória. Quando seu site estiver com várias visitas no site, execute o seguinte comando:

for pid in $(ps aux | grep fpm | grep "pool www" | awk '{print $2}'); do pmap -d $pid | tail -1 ; done | sed 's/K//' | awk '{sum+=$4} END {print sum/NR/1024}'

O comando irá mostrar o uso médio em MB de cada processo FPM para o pool www. Altere para o pool com o nome que você criou para ter a resposta correta. Desta forma você pode prever o uso de memória do seu PHP.


FacebookTwitterGoogle+Share

Comentários

HI! команда SEO для продвижения и раскрутки сайтов в поисковиках и/или социальных интернет-сетях. Меня зовут Антон, я учредитель группы link builders, линкбилдеров, копирайтеров, рерайтеров/копирайтеров, специалистов, маркетологов, оптимизаторов, профессионалов, разработчиков. Мы - команда опытных фрилансеров. Мы несомненно поможем вашему проекту подняться в топ 10 в выдаче поисковой машины различной системе. Мы предлагаем качественную раскрутку online-сайтов в поисковых системах! СЕО-специалисты которые работают в команде прошли громадный профессиональный путь, нам известно, каким способом грамотно организовывать ваш личный веб-сайт, продвинуть его на 1 место, трансформировать веб-трафик в заказы. Наша стцдияпредлагает вам абсолютно бесплатное предложение по продвижению ваших онлайн-сайтов. Ждем Вас.

seo продвижение сайта бесплатно сео анализ сайта онлайн бесплатно

Hello, what is the exact benefit please to use mod_fastcgi instead of proxying all request with mod_proxy_fcgi to fpm? It sounds to me as another layer which is not necessary because FPM itself is FastCGI implementation. Thanks for explanation.

Привет! команда по поисковой оптимизации для продвижения и раскрутки online-проектов в поисковых системах и/или социальных интернет-сетях. И меня зовут Антон, я основатель группы профессионалов, оптимизаторов, специалистов, link builders, маркетологов, рерайтеров/копирайтеров, разработчиков, копирайтеров, линкбилдеров. Мы — команда амбициозных специалистов с восьмилетним опытом работы в области фриланса. Данные специалисты вам взять топ 3 в поисковой выдаче любой системе. Для вас мы предлагаем высококачественную раскрутку интернет-ресурсов в поисковых сервисах! У всех абсолютно работников представленной команды за плечами гигантский профессиональный путь, нам известно, как грамотно организовывать ваш личный сайт, продвинуть его на 1 место, преобразовать веб-трафик в заказы. Мы предлагаем совершенно бесплатное предложение по раскрутке любых web-сайтов. Мы ждем Вас.

системы продвижения сайта бесплатно сео сайта бесплатно онлайн

Our goal at vape4style.com is to deliver our clients along with the greatest vaping knowledge achievable, helping them vape with style!. Located in New York City and in company since 2015, our experts are a custom-made vaping superstore offering all forms of vape mods, e-liquids, pure nicotine sodiums, hull bodies, tanks, coils, as well as various other vaping extras, including batteries as well as external battery chargers. Our e-juices are actually regularly fresh given that our experts certainly not simply sell our items retail, but also distribute to nearby New York City shops and also offer wholesale options. This enables our team to consistently revolve our supply, delivering our customers and also retail stores along with one of the most best inventory possible.

If you are actually a vaper or making an effort to leave smoke cigarettes, you reside in the best area. Wish to conserve some amount of money in process? Rush as well as join our email subscriber list to obtain exclusive nightclub VIP, vape4style markdowns, promos and also cost-free giveaways!

Our team are actually an special Northeast Yihi distributor. We are likewise licensed reps of Negative Drip, Marina Vape, Charlie's Chalk Dirt, Beard Vape, SVRF by Saveur Vape, Ripe Vapes, Smok, Segeli, Lost Vape, Kangertech, Triton as well as many more. Don't find something you are looking for on our site? Not a complication! Only allow us understand what you are seeking and our company will definitely locate it for you at a affordable rate. Have a inquiry regarding a specific item? Our vape specialists will rejoice to supply even more information regarding anything our team offer. Simply send our company your inquiry or even phone our team. Our team will certainly be glad to aid!

#5 by beard vape outlet = Yihi Mini T

Our objective at vape4style.com is actually to deliver our customers along with the greatest vaping adventure possible, helping them vape snappy!. Based in New York City and in business since 2015, our company are a customized vaping superstore offering all types of vape mods, e-liquids, nicotine sodiums, covering devices, storage tanks, rolls, and various other vaping accessories, like electric batteries and exterior wall chargers. Our e-juices are regularly clean since we not just sell our products retail, however likewise circulate to regional NYC shops and also supply retail possibilities. This allows us to consistently turn our sell, supplying our clients and also shops along with the most freshest stock achievable.

If you are actually a vaper or even attempting to leave smoke, you remain in the ideal location. Would like to save some loan present? Hurry as well as join our email mailing list to obtain exclusive nightclub VIP, vape4style savings, promotions as well as free giveaways!

We are an unique Northeast Yihi distributor. Our team are actually also authorized reps of Bad Drip, Port Vape, Charlie's Chalk Dust, Beard Vape, SVRF through Saveur Vape, Ripe Vapes, Smok, Segeli, Lost Vape, Kangertech, Triton and also much more. Don't see something you are actually trying to find on our web site? Certainly not a issue! Just let our team know what you are trying to find and our company will definitely discover it for you at a reduced price. Possess a question regarding a certain item? Our vape professionals will definitely rejoice to supply even more details about anything our experts sell. Simply send us your concern or even phone our team. Our group is going to rejoice to help!

premium e-liquid brands shopping - Yihi T

Company cleaning Downtown Manhattan - hire cleaning service

Our specialists Rochdale Village spend spring garden cleaning.

Our Partnership organization carries out spring cleaning 2018 in areas , we can put in order your house square, apartment, tanhaus.

Our Partnership cleaning company Wards Island DAWN, is engaged spring cleaning site urgently in Breezy Point under the direction of WILLIAMSON.

Today, cleaning in the spring time is a good case to do cleaning work, on the street, at home.
Streets, courtyards, parks, squares and urban square need not only clear after last winter Today cleaning with the onset of spring is an opportunity implement cleaning the house, on the street, at home.
Roads, courtyards, gardens, squares and urban territories not only clean up after last winter, take out the garbage, but also prepare for the summer period. For this purpose it is necessary to restore damaged sidewalks and curbs, repair broken small architectural forms sculptures, flowerpots,artificial reservoirs,benches, fences, and so on, refresh fences, painting and many other things.
Our firm does spring cleaning 2019 in the district, but with joy we will certainly help tidy up .
Our specialists Fresh Meadows can hold spring cleaning plot.

Агрегатор Яндекс такси Самара позволяет людям вызвать авто в любое удобное вам время. Сделать заказ авто вы можете тремя способами: на сайте Яндекс такси, через оператора позвонив нам или воспользовавшись мобильным приложением. Вам требуется назвать время когда нужна автомобиль, свой номер сотового телефона, местоположение.

Заказывают Я. такси с детским креслом для перевозки детей, вечером после встреч лучше всего воспользоваться Яндекс такси, чем, например, садиться в авто нетрезвым, на вокзал или в аэропорт удобнее пользоваться Я. такси и даже не искать где разместить свою машину. Оплата выполняется безналичным или наличным платежом. Время подъезда Yandex такси составляет от 5 до десяти минут примерно.

Плюсы работы в Яндекс такси: Быстрая регистрация в приложение, Не очень большая комиссия, Выплаты мгновенные, Постоянный поток заявок, Диспетчер круглосуточно на связи.

Для выполнения работ в Я. такси водителю надо зарегистрироваться самому и транспорт, перечисленное займёт 5 минут. Наша комиссия будет составлять не больше 20 %. Вы можете с легкость получать зарплату в любое время. У вас постоянно обязательно будут заказы. В случае вопросов можно связаться с постоянно действующей службой поддержки. Яндекс такси даёт возможность гражданам быстро доехать до нужного места. Заказывая современное Яндекс такси вы получите шикарный сервис в г. Самара.

работа в такси на своей машине - [url=https://centrsnab163.ru]работа в компании такси[/url]

Comentar

HTML restrito

  • Tags HTML permitidas: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Quebras de linhas e parágrafos são gerados automaticamente.
  • Web page addresses and email addresses turn into links automatically.
Categoria