One place for hosting & domains

      PHPFPM

      How To Configure Apache HTTP with MPM Event and PHP-FPM on Ubuntu 18.04


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      The Apache HTTP web server has evolved through the years to work in different environments and solve different needs. One important problem Apache HTTP has to solve, like any web server, is how to handle different processes to serve an http protocol request. This involves opening a socket, processing the request, keeping the connection open for a certain period, handling new events occurring through that connection, and returning the content produced by a program made in a particular language (such as PHP, Perl, or Python). These tasks are performed and controlled by a Multi-Processing Module (MPM).

      Apache HTTP comes with three different MPM:

      • Pre-fork: A new process is created for each incoming connection reaching the server. Each process is isolated from the others, so no memory is shared between them, even if they are performing identical calls at some point in their execution. This is a safe way to run applications linked to libraries that do not support threading—typically older applications or libraries.
      • Worker: A parent process is responsible for launching a pool of child processes, some of which are listening for new incoming connections, and others are serving the requested content. Each process is threaded (a single thread can handle one connection) so one process can handle several requests concurrently. This method of treating connections encourages better resource utilization, while still maintaining stability. This is a result of the pool of available processes, which often has free available threads ready to immediately serve new connections.
      • Event: Based on worker, this MPM goes one step further by optimizing how the parent process schedules tasks to the child processes and the threads associated to those. A connection stays open for 5 seconds by default and closes if no new event happens; this is the keep-alive directive default value, which retains the thread associated to it. The Event MPM enables the process to manage threads so that some threads are free to handle new incoming connections while others are kept bound to the live connections. Allowing re-distribution of assigned tasks to threads will make for better resource utilization and performance.

      The MPM Event module is a fast multi-processing module available on the Apache HTTP web server.

      PHP-FPM is the FastCGI Process Manager for PHP. The FastCGI protocol is based on the Common Gateway Interface (CGI), a protocol that sits between applications and web servers like Apache HTTP. This allows developers to write applications separately from the behavior of web servers. Programs run their processes independently and pass their product to the web server through this protocol. Each new connection in need of processing by an application will create a new process.

      By combining the MPM Event in Apache HTTP with the PHP FastCGI Process Manager (PHP-FPM) a website can load faster and handle more concurrent connections while using fewer resources.

      In this tutorial you will improve the performance of the LAMP stack by changing the default multi-processing module from pre-fork to event and by using the PHP-FPM process manager to handle PHP code instead of the classic mod_php in Apache HTTP.

      Prerequisites

      Before you begin this guide you’ll need the following:

      Step 1 — Changing the Multi-Processing Module

      Ubuntu inherits scripts to enable or disable Apache HTTP modules from its parent distribution, Debian. You’ll use this toolset in this step to disable the Pre-fork module and enable the Event module.

      In this step you will stop Apache HTTP, disable the PHP 7.2 module linked to the Pre-fork module, and then disable Pre-fork to immediately enable the Event module.

      First you’ll stop the Apache HTTP service:

      • sudo systemctl stop apache2

      Now you can disable the PHP 7.2 module, which is related to the Pre-fork module:

      Then disable the Pre-fork MPM module:

      • sudo a2dismod mpm_prefork

      Now enable the Event MPM module:

      You’ve switched the MPM from pre-fork to event and removed the PHP 7.2 module connection between PHP and Apache HTTP. In the next step you’ll install the php-fpm module, as well as the related libraries and proxy modules. You’ll configure Apache HTTP so that it can communicate with PHP too.

      Step 2 — Configuring Apache HTTP to Use the FastCGI Process Manager

      At this stage you’ve switched the way Apache HTTP processes connections by moving from the Pre-fork MPM to Event. However along the way you’ve disabled the PHP module that connected Apache HTTP with any program running on PHP.

      In this step you’ll install the PHP-FPM processor so Apache HTTP is again able to process PHP programs. And you’ll also install the dependency libraries and enable the modules so both can cooperate smoothly and quicker than before.

      First install php-fpm. The following command will install the PHP-FPM package and it will automatically enable the php7.2-fpm service integrated with systemd, so the service is started at boot time:

      In order to communicate, Apache HTTP and PHP need a library enabling that capacity. You’ll now install libapache2-mod-fcgid, which is able to serve as an interface between programs with web servers, and it’s specific to Apache HTTP. This communication will happen through a UNIX socket.

      Install this library:

      • sudo apt install libapache2-mod-fcgid

      You’ve installed php-fpm and the libapache2-mod-fcgid, but neither are enabled yet.

      First enable the php-fpm module with the following command:

      Second enable Apache HTTP proxy module:

      Third enable the FastCGI proxy module in Apache HTTP:

      Note: You can read the configuration of this interaction between PHP programs and Apache HTTP through a UNIX socket with the following:

      • cat /etc/apache2/conf-enabled/php7.2-fpm.conf

      Everything is now in place so you can start Apache HTTP. You’ll make a configuration check first:

      • sudo apachectl configtest

      Output

      Syntax OK

      After that you can proceed to restart Apache HTTP, since it was automatically started when installing the FastCGI library libapache2-mod-fcgid:

      • sudo systemctl restart apache2

      You’ve installed the php-fpm module, configured Apache HTTP to work with it, enabled the necessary modules for the FastCGI protocol to work, and started the corresponding services.

      Now that Apache has the Event MPM module enabled and PHP-FPM is present and running, it is time to check everything is working as intended.

      Step 3 — Checking Your Configuration

      In order to check that the configuration changes have been applied you’ll run some tests. The first one will check what multi-processing module Apache HTTP is using. The second will verify that PHP is using the FPM manager.

      Check the Apache HTTP server by running the following command:

      • sudo apachectl -M | grep 'mpm'

      Your output will be as follows:

      Output

      mpm_event_module (shared)

      You can repeat the same for the proxy module and FastCGI:

      • sudo apachectl -M | grep 'proxy'

      The output will show:

      Output

      proxy_module (shared) proxy_fcgi_module (shared)

      If you would like to see the entire list of the modules, you can remove the the second part of the command after -M.

      It is now time to check if PHP is using the FastCGI Process Manager. To do so you’ll write a small PHP script that will show you all the information related to PHP.

      Run the following command to write a file named as follows:

      • sudo nano /var/www/your_domain/info.php

      Add the following content into the info.php file:

      info.php

      <?php phpinfo(); ?>
      

      Now visit your server’s URL and append info.php at the end like so: http://your_domain/info.php.

      The server API entry will be FPM/FastCGI.

      PHP Screen the Server API entry FPM/FastCGI

      Delete the info.php file after this check so no information about the server is publicly disclosed:

      • sudo rm /var/www/yourdomain.com/info.php

      You’ve checked the working status of the MPM module, the modules handling the FastCGI and the handling of PHP code.

      Conclusion

      You’ve optimized your original LAMP stack, so the number of connections to create new Apache HTTP processes has increased, PHP-FPM will handle PHP code more efficiently, and overall resource utilization has improved.

      See the Apache HTTP server project documentation for more information on the different modules and related projects.



      Source link

      Запуск нескольких версий PHP на одном сервере с использованием Apache и PHP-FPM в Debian 10


      Автор выбрал COVID-19 Relief Fund для получения пожертвования в рамках программы Write for DOnations.

      Введение

      Веб-сервер Apache использует виртуальные хосты для управления несколькими доменами в одной системе. PHP-FPM использует демона для управления несколькими версиями PHP в одной системе. Вы можете использовать Apache и PHP-FPM для одновременного хостинга на одном сервере нескольких веб-приложений PHP на основе разных версий PHP. Эта возможность полезна, поскольку разным приложениям могут требоваться разные версии PHP, но некоторые серверные комплексы, в том числе стек LAMP в стандартной конфигурации, могут работать только с одной версией. Сочетание Apache с PHP-FPM более экономично по сравнению с хостингом каждого приложения на отдельном экземпляре сервера.

      Также PHP-FPM предлагает разные варианты конфигурации для регистрации данных stderr и stdout, аварийной перезагрузки и адаптивного создания процессов, что полезно для сайтов с высокой нагрузкой. Использование Apache с PHP-FPM — один из лучших вариантов хостинга приложений PHP, особенно с точки зрения производительности.

      В этом обучающем руководстве мы настроим два сайта PHP для работы на одном экземпляре сервера. Каждый сайт будет использовать собственный домен, и на каждом домене будет использоваться собственная версия PHP. Первый сайт site1.your_domain развернет PHP 7.0. Второй сайт site2.your_domain развернет PHP 7.2.

      Предварительные требования

      • Один сервер Debian 10 с не менее чем 1 ГБ оперативной памяти, настроенный согласно руководству Начальная настройка сервера Debian 10, с пользователем non-root user с привилегиями sudo и брандмауэром.
      • Веб-сервер Apache, установленный и настроенный в соответствии с указаниями руководства Установка веб-сервера Apache в Debian 10.
      • Доменное имя, настроенное так, чтобы указывать на ваш сервер Debian 10. Информацию о том, как сделать так, чтобы домены указывали на дроплеты DigitalOcean, можно найти в руководстве Создание указаний на серверы имен DigitalOcean из общих реестров доменов. Для целей настоящего обучающего руководства мы используем два субдомена, каждый из которых указан с записью A в наших настройках DNS: site1.your_domain и site2.your_domain.

      Шаг 1 — Установка PHP версий 7.0 и 7.2 с помощью PHP-FPM

      Выполнив предварительные требования, вы можете установить PHP версий 7.0 и 7.2, а также PHP-FPM и некоторые дополнительные расширения. Для этого предварительно необходимо добавить в систему репозиторий sury php.

      Вначале установите требуемые пакеты, в том числе curl, wget и gnupg2:

      • sudo apt-get install curl wget gnupg2 ca-certificates lsb-release apt-transport-https -y

      Вышеуказанные пакеты позволяют получить безопасный доступ к репозиторию sury php. sury php — это сторонний репозиторий или PPA (архив персональных пакетов). Он предоставляет PHP 7.4, 7.3, 7.2, 7.1 и 7.0 для операционной системы Debian. Также он включает более актуальные версии PHP, чем содержащиеся в официальных репозиториях Debian 10, и позволяет устанавливать несколько версий PHP в одной системе.

      Затем импортируйте ключ пакета:

      • wget https://packages.sury.org/php/apt.gpg
      • sudo apt-key add apt.gpg

      Теперь добавьте в систему репозиторий sury php:

      • echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/php7.list

      Обновите репозиторий:

      Установите php7.0, php7.0-fpm, php7.0-mysql, libapache2-mod-php7.0 и libapache2-mod-fcgid с помощью следующих команд:

      • sudo apt-get install php7.0 php7.0-fpm php7.0-mysql libapache2-mod-php7.0 libapache2-mod-fcgid -y
      • php7.0 — это метапакет, который можно использовать для запуска приложений PHP.
      • php7.0-fpm предоставляет интерпретатор Fast Process Manager, который работает как демон и принимает запросы Fast/CGI.
      • php7.0-mysql связывает PHP с базой данных MySQL.
      • libapahce2-mod-php7.0 предоставляет модуль PHP для веб-сервера Apache.
      • libapache2-mod-fcgid содержит mod_fcgid, запускающий несколько экземпляров программы CGI для обработки одновременных запросов.

      Повторите процедуру для PHP версии 7.2. Установите php7.2, php7.2-fpm, php7.2-mysql и libapache2-mod-php7.2.

      • sudo apt-get install php7.2 php7.2-fpm php7.2-mysql libapache2-mod-php7.2 -y

      После установки обеих версий PHP запустите службу php7.0-fpm:

      • sudo systemctl start php7.0-fpm

      Затем проверьте статус службы php7.0-fpm:

      • sudo systemctl status php7.0-fpm

      Вывод должен выглядеть так:

      Output

      ● php7.0-fpm.service - The PHP 7.0 FastCGI Process Manager Loaded: loaded (/lib/systemd/system/php7.0-fpm.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2020-04-04 08:51:47 UTC; 1min 17s ago Docs: man:php-fpm7.0(8) Main PID: 13016 (php-fpm7.0) Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec" Tasks: 3 (limit: 1149) Memory: 19.1M CGroup: /system.slice/php7.0-fpm.service ├─13016 php-fpm: master process (/etc/php/7.0/fpm/php-fpm.conf) ├─13017 php-fpm: pool www └─13018 php-fpm: pool www Apr 04 08:51:47 debian10 systemd[1]: Starting The PHP 7.0 FastCGI Process Manager... Apr 04 08:51:47 debian10 systemd[1]: Started The PHP 7.0 FastCGI Process Manager.

      Повторите процедуру и запустите службу php7.2-fpm:

      • sudo systemctl start php7.2-fpm

      Затем проверьте статус службы php7.2-fpm:

      • sudo systemctl status php7.2-fpm

      Вывод должен выглядеть так:

      Output

      ● php7.2-fpm.service - The PHP 7.2 FastCGI Process Manager Loaded: loaded (/lib/systemd/system/php7.2-fpm.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2020-04-04 08:52:52 UTC; 1min 32s ago Docs: man:php-fpm7.2(8) Process: 22207 ExecStartPost=/usr/lib/php/php-fpm-socket-helper install /run/php/php-fpm.sock /etc/php/7.2/fpm/pool.d/www.conf 72 (code=exite Main PID: 22204 (php-fpm7.2) Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec" Tasks: 3 (limit: 1149) Memory: 12.0M CGroup: /system.slice/php7.2-fpm.service ├─22204 php-fpm: master process (/etc/php/7.2/fpm/php-fpm.conf) ├─22205 php-fpm: pool www └─22206 php-fpm: pool www Apr 04 08:52:52 debian10 systemd[1]: Starting The PHP 7.2 FastCGI Process Manager... Apr 04 08:52:52 debian10 systemd[1]: Started The PHP 7.2 FastCGI Process Manager.

      В заключение необходимо активировать несколько модулей, чтобы служба Apache2 могла работать с несколькими версиями PHP:

      • sudo a2enmod actions fcgid alias proxy_fcgi
      • actions используется для выполнения скриптов CGI на основе типа носителя или метода запроса.

      • fcgid — это высокопроизводительная альтернатива mod_cgi, запускающая достаточное количество экземпляров программы CGI для одновременной обработки запросов.

      • alias позволяет создавать схемы разных деталей файловой системы хоста в дереве документов и для целей переадресации URL.

      • proxy_fcgi позволяет Apache перенаправлять запросы PHP-FPM.

      Перезапустите службу Apache, чтобы применить изменения:

      • sudo systemctl restart apache2

      Мы установили на сервере две версии PHP. Теперь создадим структуру директорий для каждого сайта, который будем развертывать.

      Шаг 2 — Создание структур директорий для обоих сайтов

      В этом разделе мы создадим корневую директорию документов и страницу индекса для каждого из двух сайтов.

      Вначале создайте корневые директории документов для site1.your_domain и site2.your_domain:

      • sudo mkdir /var/www/site1.your_domain
      • sudo mkdir /var/www/site2.your_domain

      По умолчанию веб-сервер Apache работает как пользователь www-data и группа www-data. Чтобы убедиться в правильности структуры владения и разрешений для корневых директорий вашего сайта, используйте следующие команды:

      • sudo chown -R www-data:www-data /var/www/site1.your_domain
      • sudo chown -R www-data:www-data /var/www/site2.your_domain
      • sudo chmod -R 755 /var/www/site1.your_domain
      • sudo chmod -R 755 /var/www/site2.your_domain

      Далее вы создадите файл info.php в корневой директории каждого сайта. В нем будет отображаться информация о версии PHP для каждого сайта. Начнем с site1:

      • sudo nano /var/www/site1.your_domain/info.php

      Добавьте следующую строку:

      /var/www/site1.your_domain/info.php

      <?php phpinfo(); ?>
      

      Сохраните и закройте файл. Скопируйте созданный файл info.php в site2:

      • sudo cp /var/www/site1.your_domain/info.php /var/www/site2.your_domain/info.php

      Теперь на вашем веб-сервере должны иметься корневые директории документов, которые требуются каждому сайту для предоставления данных посетителям. Далее мы настроим веб-сервер Apache для работы с двумя разными версиями PHP.

      Шаг 3 — Настройка Apache для обоих сайтов

      В этом разделе мы создадим два файла конфигурации виртуального хоста. Это позволит двум нашим сайтам одновременно работать с двумя разными версиями PHP.

      Для обслуживания этого контента Apache необходимо создать файл виртуального хоста с правильными директивами. Вместо изменения файла конфигурации по умолчанию /etc/apache2/sites-available/000-default.conf мы создадим два новых файла в директории /etc/apache2/sites-available/.

      Вначале создайте новый файл конфигурации виртуального хоста для сайта site1.your_domain. Здесь вы предписываете Apache использовать для рендеринга содержимого php7.0:

      • sudo nano /etc/apache2/sites-available/site1.your_domain.conf

      Добавьте в файл следующее. Убедитесь, что путь к директории сайта, имя сервера и версия PHP соответствуют вашей системе:

      /etc/apache2/sites-available/site1.your_domain.conf

      
      <VirtualHost *:80>
           ServerAdmin admin@site1.your_domain
           ServerName site1.your_domain
           DocumentRoot /var/www/site1.your_domain
           DirectoryIndex info.php
      
           <Directory /var/www/site1.your_domain>
              Options Indexes FollowSymLinks MultiViews
              AllowOverride All
              Order allow,deny
              allow from all
           </Directory>
      
          <FilesMatch .php$>
            # For Apache version 2.4.10 and above, use SetHandler to run PHP as a fastCGI process server
            SetHandler "proxy:unix:/run/php/php7.0-fpm.sock|fcgi://localhost"
          </FilesMatch>
      
           ErrorLog ${APACHE_LOG_DIR}/site1.your_domain_error.log
           CustomLog ${APACHE_LOG_DIR}/site1.your_domain_access.log combined
      </VirtualHost>
      

      В этом файле вы изменили директорию на DocumentRoot, а ServerAdmin на адрес электронной почты, доступный администратору сайта your_domain. Также вы изменили параметр ServerName, устанавливающий базовый домен для этой конфигурации виртуального хоста, и добавили директиву SetHandler для запуска PHP как сервера процессов fastCGI.

      Сохраните и закройте файл.

      Теперь создайте новый файл конфигурации виртуального хоста для сайта site2.your_domain. Для этого субдомена мы будем развертывать php7.2:

      • sudo nano /etc/apache2/sites-available/site2.your_domain.conf

      Добавьте в файл следующее. Убедитесь, что путь к директории сайта, имя сервера и версия PHP соответствуют уникальным параметрам вашей системы:

      /etc/apache2/sites-available/site2.your_domain.conf

      <VirtualHost *:80>
           ServerAdmin admin@site2.your_domain
           ServerName site2.your_domain
           DocumentRoot /var/www/site2.your_domain
           DirectoryIndex info.php  
      
           <Directory /var/www/site2.your_domain>
              Options Indexes FollowSymLinks MultiViews
              AllowOverride All
              Order allow,deny
              allow from all
           </Directory>
      
          <FilesMatch .php$>
            # For Apache version 2.4.10 and above, use SetHandler to run PHP as a fastCGI process server
            SetHandler "proxy:unix:/run/php/php7.2-fpm.sock|fcgi://localhost"
          </FilesMatch>
      
           ErrorLog ${APACHE_LOG_DIR}/site2.your_domain_error.log
           CustomLog ${APACHE_LOG_DIR}/site2.your_domain_access.log combined
      </VirtualHost>
      

      Сохраните файл и закройте его после завершения. Проверьте файл конфигурации Apache на наличие синтаксических ошибок:

      • sudo apachectl configtest

      Вывод должен выглядеть так:

      Output

      Syntax OK

      Активируйте оба файла конфигурации виртуального хоста:

      • sudo a2ensite site1.your_domain
      • sudo a2ensite site2.your_domain

      Отключите сайт по умолчанию, поскольку он не потребуется:

      • sudo a2dissite 000-default.conf

      Перезапустите службу Apache, чтобы применить изменения:

      • sudo systemctl restart apache2

      Мы настроили Apache для обслуживания каждого из сайтов и теперь протестируем их и убедимся, что на них работают правильные версии PHP.

      Шаг 4 — Тестирование сайтов

      Мы настроили два сайта для работы с двумя разными версиями PHP. Теперь проверим результаты.

      Откройте в браузере сайты http://site1.your_domain и http://site2.your_domain. Вы увидите две страницы, выглядящие следующим образом:

      Информационная страница PHP 7.0Информационная страница PHP 7.2

      Обратите внимание на заголовки. На первой странице указано, что на сайте site1.your_domain развернута версия PHP 7.0. На второй странице указано, что на сайте site2.your_domain развернута версия PHP 7.2.

      Мы протестировали сайты и теперь можем удалить файлы info.php. Эти файлы представляют собой угрозу безопасности, поскольку они содержат важную информацию о вашем сервере и при этом доступны неуполномоченным пользователям. Чтобы удалить оба файла, запустите следующие команды:

      • sudo rm -rf /var/www/site1.your_domain/info.php
      • sudo rm -rf /var/www/site2.your_domain/info.php

      Теперь у вас имеется один сервер Debian 10, обслуживающий два сайта с разными версиями PHP. Однако PHP-FPM можно применять и для других целей.

      Заключение

      Мы объединили виртуальные хосты и PHP-FPM для обслуживания нескольких сайтов и нескольких версий PHP на одном сервере. Количество сайтов PHP и версий PHP, которые может обслуживать ваш сервер Apache, зависит исключительно от вычислительной мощности вашего экземпляра.

      Теперь вы можете начать изучение более сложных функций PHP-FPM, таких как процесс адаптивного создания или функции регистрации sdtout и stderr. Также вы можете заняться защитой своих сайтов. Для этого используйте наш обучающий модуль по защите сайтов с помощью бесплатных сертификатов TLS/SSL от Let’s Encrypt.



      Source link

      Comment exécuter plusieurs Versions PHP sur un serveur en utilisant Apache et PHP-FPM sur Debian 10


      L’auteur a choisi le COVID-19 Relief Fund pour recevoir un don dans le cadre du programme Write for DOnations.

      Introduction

      Le serveur web Apache utilise des hôtes virtuels pour gérer plusieurs domaines sur une seule instance. De même, PHP-FPM utilise un démon pour gérer plusieurs versions PHP sur une seule instance. Vous pouvez utiliser ensemble Apache et PHP-FPM pour héberger plusieurs applications Web PHP, chacune utilisant une version différente de PHP, toutes sur le même serveur, et toutes en même temps. C’est utile car différentes applications peuvent nécessiter différentes versions de PHP, mais certaines piles de serveurs, telles qu’une pile LAMP régulièrement configurée, ne peuvent gérer qu’une seule version. Combiner Apache avec PHP-FPM est également une solution plus économique que d’héberger chaque application sur sa propre instance.

      PHP-FPM offre également des options de configuration pour la journalisation stderr et stdout, les redémarrages d’urgence et le lancement de processus adaptatifs, ce qui est utile pour les sites très chargés. En fait, l’utilisation d’Apache avec PHP-FPM est l’une des meilleures piles pour héberger des applications PHP, surtout en matière de performances.

      Dans ce tutoriel, vous allez configurer deux sites PHP sur une seule instance. Chaque site utilisera son propre domaine, et chaque domaine déploiera sa propre version de PHP. Le premier, site1.your_domain, déploiera PHP 7.0. La deuxième, site2.your_domain, déploiera PHP 7.2.

      Conditions préalables

      Étape 1 – Installation des Versions PHP 7.0 et 7.2 avec PHP-FPM

      Une fois les conditions préalables remplies, vous allez maintenant installer les versions 7.0 et 7.2, ainsi que PHP-FPM et plusieurs extensions supplémentaires. Mais pour ce faire, vous devrez d’abord ajouter le référentiel sury php à votre système.

      Installez d’abord les différents paquets nécessaires, notamment curl, wget, and gnupg2 :

      • sudo apt-get install curl wget gnupg2 ca-certificates lsb-release apt-transport-https -y

      Les paquets ci-dessus vous permettront d’accéder au référentiel sury php, et ce de manière sécurisée. sury php est un référentiel tiers ou PPA (personal package archive ou dépôts personnels de paquets logiciels, en français). Il offre PHP 7.4, 7.3, 7.2, 7.1, et 7.0 pour le système d’exploitation Debian. Il offre également des versions plus récentes de PHP que les référentiels officiels de Debian 10 et vous permettra d’installer plusieurs versions de PHP sur le même système.

      Ensuite, importez la clé du paquet :

      • wget https://packages.sury.org/php/apt.gpg
      • sudo apt-key add apt.gpg

      Ajoutez maintenant le référentiel sury php à votre système :

      • echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/php7.list

      Mettez le référentiel à jour :

      Ensuite, installez php7.0, php7.0-fpm, php7.0-mysql, libapache2-mod-php7.0 et libapache2-mod-fcgid avec les commandes suivantes

      • sudo apt-get install php7.0 php7.0-fpm php7.0-mysql libapache2-mod-php7.0 libapache2-mod-fcgid -y
      • php7.0 est un meta package qui peut être utilisé pour exécuter des applications PHP.
      • php7.0-fpm fournit l’interprète Fast Process Manager qui fonctionne comme démon et reçoit des requêtes Fast/CGI.
      • php7.0-mysql connecte PHP à la base de données MySQL.
      • libapahce2-mod-php7.0 fournit le module PHP pour le serveur Apache.
      • libapache2-mod-fcgid contient un mod_fcgid qui lance un certain nombre d’instances de programme CGI pour traiter les requêtes simultanées.

      Repérez maintenant le processus pour la version PHP 7.2. Installez php7.2, php7.2-fpm, php7.2-mysql, et libapache2-mod-php7.2 :

      • sudo apt-get install php7.2 php7.2-fpm php7.2-mysql libapache2-mod-php7.2 -y

      Après avoir installé les deux versions PHP, lancez le service php7.0-fpm

      • sudo systemctl start php7.0-fpm

      Ensuite, vérifiez l’état du service php7.0-fpm

      • sudo systemctl status php7.0-fpm

      Vous verrez la sortie suivante :

      Output

      ● php7.0-fpm.service - The PHP 7.0 FastCGI Process Manager Loaded: loaded (/lib/systemd/system/php7.0-fpm.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2020-04-04 08:51:47 UTC; 1min 17s ago Docs: man:php-fpm7.0(8) Main PID: 13016 (php-fpm7.0) Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec" Tasks: 3 (limit: 1149) Memory: 19.1M CGroup: /system.slice/php7.0-fpm.service ├─13016 php-fpm: master process (/etc/php/7.0/fpm/php-fpm.conf) ├─13017 php-fpm: pool www └─13018 php-fpm: pool www Apr 04 08:51:47 debian10 systemd[1]: Starting The PHP 7.0 FastCGI Process Manager... Apr 04 08:51:47 debian10 systemd[1]: Started The PHP 7.0 FastCGI Process Manager.

      En répétant ce processus, lancez maintenant le service php7.2-fpm :

      • sudo systemctl start php7.2-fpm

      Vérifiez ensuite l’état du service php7.2-fpm :

      • sudo systemctl status php7.2-fpm

      Vous verrez la sortie suivante :

      Output

      ● php7.2-fpm.service - The PHP 7.2 FastCGI Process Manager Loaded: loaded (/lib/systemd/system/php7.2-fpm.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2020-04-04 08:52:52 UTC; 1min 32s ago Docs: man:php-fpm7.2(8) Process: 22207 ExecStartPost=/usr/lib/php/php-fpm-socket-helper install /run/php/php-fpm.sock /etc/php/7.2/fpm/pool.d/www.conf 72 (code=exite Main PID: 22204 (php-fpm7.2) Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec" Tasks: 3 (limit: 1149) Memory: 12.0M CGroup: /system.slice/php7.2-fpm.service ├─22204 php-fpm: master process (/etc/php/7.2/fpm/php-fpm.conf) ├─22205 php-fpm: pool www └─22206 php-fpm: pool www Apr 04 08:52:52 debian10 systemd[1]: Starting The PHP 7.2 FastCGI Process Manager... Apr 04 08:52:52 debian10 systemd[1]: Started The PHP 7.2 FastCGI Process Manager.

      Et enfin, vous devez activer plusieurs modules pour que votre service Apache2 puisse fonctionner avec plusieurs versions PHP :

      • sudo a2enmod actions fcgid alias proxy_fcgi
      • actions est utilisé pour exécuter des scripts CGI sur la base de type de média ou de méthode de requête.

      • fcgid est une alternative haute performance à mod_cgi qui démarre un nombre suffisant d’instances du programme CGI pour traiter des requêtes simultanées.

      • alias permet le mappage des différentes parties du système de fichiers hôte dans l’arborescence du document, et la redirection des URL.

      • proxy_fcgi permet à Apache de transmettre des requêtes à PHP-FPM.

      Redémarrez maintenant le service Apache pour appliquer vos modifications :

      • sudo systemctl restart apache2

      À ce stade, vous avez installé deux versions PHP sur votre serveur. Ensuite, vous allez créer une structure de répertoire pour chaque site web que vous voulez déployer.

      Étape 2 — Création de structures répertoire pour les deux sites Web

      Dans cette section, vous créerez un répertoire root de document et une page index pour chacun de vos deux sites Web.

      Tout d’abord, créez des répertoires root de documents à la fois pour site1.your_domain et site2.your_domain

      • sudo mkdir /var/www/site1.your_domain
      • sudo mkdir /var/www/site2.your_domain

      Par défaut, le serveur Apache fonctionne comme un utilisateur www-data et un groupe www-data. Pour vous assurer que vous avez la propriété et les permissions correctes des répertoires root de votre site web, exécutez les commandes suivantes :

      • sudo chown -R www-data:www-data /var/www/site1.your_domain
      • sudo chown -R www-data:www-data /var/www/site2.your_domain
      • sudo chmod -R 755 /var/www/site1.your_domain
      • sudo chmod -R 755 /var/www/site2.your_domain

      Ensuite, vous allez créer un fichier info.php à l’intérieur du répertoire root de chaque site Web. Cela affichera les informations de version PHP de chaque site Web. Commencez avec site1

      • sudo nano /var/www/site1.your_domain/info.php

      Ajoutez la ligne suivante :

      /var/www/site1.your_domain/info.php

      <?php phpinfo(); ?>
      

      Enregistrez et fermez le fichier. Copiez maintenant le fichier info.php que vous avez créé sur site2

      • sudo cp /var/www/site1.your_domain/info.php /var/www/site2.your_domain/info.php

      Votre serveur web devrait maintenant disposer des répertoires racine de documents dont chaque site a besoin pour fournir des données aux visiteurs. Ensuite, vous allez configurer votre serveur web Apache pour qu’il fonctionne avec deux versions PHP différentes.

      Étape 3 — Configuration d’Apache pour les deux sites Web

      Dans cette section, vous allez créer deux fichiers de configuration d’hôte virtuel. Cela permettra à vos deux sites web de fonctionner simultanément avec deux versions PHP différentes.

      Pour qu’Apache puisse servir ce contenu, il est nécessaire de créer un fichier d’hôte virtuel avec les directives correctes. Au lieu de modifier le fichier de configuration par défaut situé à /etc/apache2/sites-available/000-default.conf​​​, vous allez en créer deux nouveaux dans le répertoire /etc/apache2/sites-available/​​​.

      Commencez par créer un nouveau fichier de configuration d’hôte virtuel pour le site Web site1.your_domain. Ici, vous allez indiquer à Apache de rendre le contenu en utilisant php7.0 :

      • sudo nano /etc/apache2/sites-available/site1.your_domain.conf

      Ajoutez le contenu suivant. Assurez-vous le chemin du répertoire du site Web, le nom du serveur et la version PHP correspondent à votre configuration :

      /etc/apache2/sites-available/site1.your_domain.conf

      
      <VirtualHost *:80>
           ServerAdmin admin@site1.your_domain
           ServerName site1.your_domain
           DocumentRoot /var/www/site1.your_domain
           DirectoryIndex info.php
      
           <Directory /var/www/site1.your_domain>
              Options Indexes FollowSymLinks MultiViews
              AllowOverride All
              Order allow,deny
              allow from all
           </Directory>
      
          <FilesMatch .php$>
            # For Apache version 2.4.10 and above, use SetHandler to run PHP as a fastCGI process server
            SetHandler "proxy:unix:/run/php/php7.0-fpm.sock|fcgi://localhost"
          </FilesMatch>
      
           ErrorLog ${APACHE_LOG_DIR}/site1.your_domain_error.log
           CustomLog ${APACHE_LOG_DIR}/site1.your_domain_access.log combined
      </VirtualHost>
      

      Dans ce fichier, vous avez mis à jour le DocumentRoot sur votre nouveau répertoire et ServerAdmin à un email auquel l’administrateur du site your_domain peut accéder. Vous avez également mis à jour ServerName, qui établit le domaine de base pour cette configuration d’hôte virtuel, et vous avez ajouté une directive SetHandler pour exécuter PHP en tant que serveur de processus fastCGI

      Enregistrez et fermez le fichier.

      Ensuite, créez un nouveau fichier de configuration d’hôte virtuel pour le site Web site2.your_domain. Vous allez spécifier ce sous domaine pour déployer php7.2

      • sudo nano /etc/apache2/sites-available/site2.your_domain.conf

      Ajoutez le contenu suivant. Là encore, assurez-vous que le chemin d’accès au répertoire du site web, le nom du serveur et la version PHP correspondent à vos informations uniques :

      /etc/apache2/sites-available/site2.your_domain.conf

      <VirtualHost *:80>
           ServerAdmin admin@site2.your_domain
           ServerName site2.your_domain
           DocumentRoot /var/www/site2.your_domain
           DirectoryIndex info.php  
      
           <Directory /var/www/site2.your_domain>
              Options Indexes FollowSymLinks MultiViews
              AllowOverride All
              Order allow,deny
              allow from all
           </Directory>
      
          <FilesMatch .php$>
            # For Apache version 2.4.10 and above, use SetHandler to run PHP as a fastCGI process server
            SetHandler "proxy:unix:/run/php/php7.2-fpm.sock|fcgi://localhost"
          </FilesMatch>
      
           ErrorLog ${APACHE_LOG_DIR}/site2.your_domain_error.log
           CustomLog ${APACHE_LOG_DIR}/site2.your_domain_access.log combined
      </VirtualHost>
      

      Enregistrez et fermez le fichier lorsque vous avez terminé. Vérifiez ensuite le fichier de configuration Apache pour détecter toute erreur de syntaxe :

      • sudo apachectl configtest

      Vous verrez la sortie suivante :

      Output

      Syntax OK

      Ensuite, activez les deux fichiers de configuration d’hôte virtuel :

      • sudo a2ensite site1.your_domain
      • sudo a2ensite site2.your_domain

      Désactivez maintenant le site par défaut, puisque vous n’en aurez pas besoin :

      • sudo a2dissite 000-default.conf

      Enfin, redémarrez le service Apache pour implémenter vos changements :

      • sudo systemctl restart apache2

      Maintenant que vous avez configuré Apache pour servir chaque site, vous allez les tester pour vous assurer que les versions PHP adéquates tournent.

      Étape 4 — Test des deux sites Web

      À ce stade, vous avez configuré deux sites web pour exécuter deux versions différentes de PHP. Testez maintenant les résultats.

      Ouvrez votre navigateur web et consultez les deux sites http://site1.your_domain et http://site2.your_domain Vous verrez deux pages qui ressemblent à ceci :

      PHP 7.0 info pagePHP 7.2 info page

      Notez les titres. La première page indique que site1.your_domain a déployé PHP version 7.0. La deuxième indique que site2.your_domain a déployé PHP version 7.2.

      Maintenant que vous avez testé vos sites, supprimez les fichiers info.php. Étant donné qu’ils contiennent des informations sensibles sur votre serveur et sont accessibles aux utilisateurs non autorisés, ils constituent une menace de sécurité. Pour supprimer les deux fichiers, exécutez les commandes suivantes :

      • sudo rm -rf /var/www/site1.your_domain/info.php
      • sudo rm -rf /var/www/site2.your_domain/info.php

      Vous disposez maintenant d’un seul serveur Debian 10 qui gère deux sites web avec deux versions PHP différentes. Cela dit, PHP-FPM n’est pas limité à cette seule application.

      Conclusion

      Vous avez maintenant combiné des hôtes virtuels et PHP-FPM pour servir plusieurs sites web et plusieurs versions de PHP sur un seul serveur. La seule limite pratique sur le nombre de sites PHP et les versions PHP que votre service Apache peut gérer est la puissance de traitement de votre instance.

      À partir de là, vous pouvez envisager d’explorer les fonctionnalités les plus avancées de PHP-FPM, comme son processus de spawning adaptatif ou la façon dont il peut enregistrer sdtout et stderr. Sinon, vous pouvez maintenant sécuriser vos sites web. Pour ce faire, vous pouvez suivre notre tutoriel sur comment sécuriser vos sites avec des certificats TLS/SSL gratuits de Let’s Encrypt.



      Source link